【问题标题】:How do I call a static child function from parent static function?如何从父静态函数调用静态子函数?
【发布时间】:2011-10-04 10:36:24
【问题描述】:

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

在 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 oop static late-static-binding


【解决方案1】:

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

相关:new self vs new static; PHP 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();

或者如果同名,使用parentPHP Manual

parent::parentFunc();

(这不是您所要求的,只是为了完整起见将其放在这里)。

Get_call_class() 已针对非常具体的情况引入,例如 late static bindings PHP Manual

Object Inheritance PHP Manual

【讨论】:

  • OT:您如何如此一致地创建文档链接?我已经在几个用户身上看到过这种情况,您是否为此使用了某种脚本?
【解决方案2】:

我怀疑你对父/子、类/对象和函数/方法有点困惑。

Ionuț G. Stan 解释了如何调用未在父类中声明的方法(正如他所说,父类应该是抽象的或实现 __call() 方法)。

但是,如果您的意思是如何从父类调用已在子类中被覆盖的方法,那么这是不可能的 - 也不应该是。考虑:

Class shape {
 ...
}

Class circle extends shape {
  function area() {

  }
} 
Class square extends shape {
  function area() {

  }
}

如果您打算在“shape”实例(没有 area 方法)上调用 area 方法,那么应该使用哪个子对象?两个子方法都将依赖于不常见/未由 shape 类实现的属性。

【讨论】:

    【解决方案3】:

    试试这个:

    <?php
     class A {
     public static function newInstance() {
    $rv = new static();  
    return $rv;
    }
    
    public function __construct() { echo " A::__construct\n"; }
    }
    class B extends A {
    public function __construct() { echo " B::__construct\n"; }
    } 
    class C extends B {
    public function __construct() { echo " C::__construct\n"; }   
    }
    ?>
    

    【讨论】:

      猜你喜欢
      • 2011-09-08
      • 1970-01-01
      • 1970-01-01
      • 2022-01-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多