How do I call a static child function from parent static function?

Sahal picture Sahal · Jul 13, 2011 · Viewed 9.8k times · Source

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();

Answer

hakre picture hakre · Jul 13, 2011

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