php - 如何从父静态函数调用静态子函数?

标签 php oop static late-static-binding

如何从父静态函数调用子函数?

在 php5.3 中有一个名为 get_called_class() 的内置方法可以从父类调用子方法。但是我的服务器运行的是 php 5.1

有什么办法可以做到这一点?

我想从静态函数中调用它。这样我就不能使用“$this”

所以我应该使用“self”关键字。

下面的例子我的父类是“Test123”,从父类静态函数“myfunc”我试图像这样调用子类函数“self::test();”

abstract class Test123
{

  function __construct()
  {
    // some code here
  }

  public static function myfunc()
  {
    self::test();
  }

  abstract function test();
}

class Test123456 extends Test123
{
  function __construct()
  {
    parent::__construct();
  }

  function test()
  {
    echo "So you managed to call me !!";
  }

}

$fish = new Test123456();
$fish->test();
$fish->myfunc();

最佳答案

编辑:您尝试实现的目标在 PHP 5.1 中是不可能的。 PHP 5.1中没有late static bindings PHP Manual,调用子函数需要显式命名子类:Test123456::test()self会是Test123 在类 Test123 的静态函数中(始终)并且 static 关键字不可用于调用 PHP 5.1 中的静态函数。

相关:new self vs new staticPHP 5.2 Equivalent to Late Static Binding (new static)?


如果您指的是静态父函数,那么您需要为 php 5.1 中的函数调用显式命名父(或子)函数:

parentClass::func();
Test123456::test();

在 PHP 5.3 中,您可以使用 static 关键字 PHP Manual 来解析被调用类的名称:

static::func();
static::test();

如果它们是非静态的,只需使用 $this PHP Manual :

$this->parentFunc();
$this->childFunc();

或者如果它有相同的名字,使用parent PHP Manual :

parent::parentFunc();

(这不完全是您要求的,只是为了完整性而将其放在这里)。

Get_called_class() 已针对非常特殊的情况引入,例如 late static bindings PHP Manual

参见 Object Inheritance PHP Manual

关于php - 如何从父静态函数调用静态子函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6678466/

相关文章:

php - 从分层树中选择最深的项目时,Drupal 6 自动重定向

java - 关于eclipse检测到代码错误并创建对象来运行方法的问题

python - 为什么在 python 中使用类方法而不是实例方法

java - 子类中的每个函数都必须在父类(super class)中定义吗?

Java - 使用静态方法中的实例类?

php - 检查数据库中的新条目

javascript - Jquery 删除不适用于克隆

php - 2 列的 CSS 布局问题

Java : Why does placement of static variable matter?

c++ - 在 Windows VC++ 2010 静态链接下构建 boost + ICU