dongyo7931 2011-07-13 11:57
浏览 46
已采纳

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

How do I call child function from parent static function ?

In php5.3 there is a built in method called get_called_class() to call child method from parent class. But my server is running with php 5.1.

Is there any way can do this ?

I want to call it from a static function . So that I can not use "$this"

So i should use "self" keyword.

Below example my parent class is "Test123" , from the parent class static function "myfunc" am trying to call child class function like this "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();
  • 写回答

3条回答 默认 最新

  • douyinyi7766 2011-07-13 12:03
    关注

    Edit: What you try to achieve is not possible with PHP 5.1. There is no late static bindings PHP Manual in PHP 5.1, you need to explicitly name the child class to call the child function: Test123456::test(), self will be Test123 in a static function of the class Test123 (always) and the static keyword is not available to call a static function in PHP 5.1.

    Related: new self vs new static; PHP 5.2 Equivalent to Late Static Binding (new static)?


    If you are referring to a static parent function, then you need to explicitly name the parent (or child) for the function call in php 5.1:

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

    In PHP 5.3 you can do this instead with the static keyword PHP Manual to resolve the called class' name:

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

    If those are non-static, just use $this PHP Manual:

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

    Or if it has the same name, use parent PHP Manual:

    parent::parentFunc();
    

    (which is not exactly what you asked for, just putting it here for completeness).

    Get_called_class() has been introduced for very specific cases like to late static bindings PHP Manual.

    See Object Inheritance PHP Manual

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题