Search code examples
phpoopstaticdynamic-variableslate-static-binding

Call static properties within another class in php


I have problem about calling a static property of a class inside another class.

Class A {

    public $property;

    public function __construct( $prop ) {
        $this->property = $prop;

    }
    public function returnValue(){
        return static::$this->property;
    }

}

Class B extends A {

    public static $property_one = 'This is first property';
    public static $property_two = 'This is second property';

}

$B = new B( 'property_one' );
$B->returnValue();

I expect to return This is first property But the Output is just the name a parameter input in __construct;

When I print_r( static::$this->property ); the output is just property_one


Solution

  • Just change:

    return static::$this->property;
    

    with:

    return static::${$this->property};