Reputation: 5262
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
Upvotes: 0
Views: 888
Reputation: 76405
There are several issues here:
$property_one
is declared in class B
, the A
class's constructor won't have access to that property, nor can you guarantee this property to be present.$this->property
happens to be assigned. What if it's assigned an object? an int, or float?static::$propery
or self::$property
. Note the $
! When you write static::$this->property
, you're expecting this to evaluate to self::property_one
. You're clearly missing the $
sign.self::${$this->property}
. Check the PHP manual on variable variables.To have access to a static property of a child class in the constructor, you can't but rely on the child's constructor:
Class A
{
public $property;
}
Class B extends A
{
public static $property_one = 'This is first property';
public static $property_two = 'This is second property';
public function __construct( $prop )
{
$this->property = $prop;
print self::${$this->property};
}
}
$B = new B( 'property_one' );
An alternative would be:
Class A
{
public $property;
public function __constructor($prop)
{
$this->property = $prop;
}
public function getProp()
{
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->getProp();
Upvotes: 1
Reputation: 5376
Just change:
return static::$this->property;
with:
return static::${$this->property};
Upvotes: 1
Reputation: 13725
Maybe like this?
<?php
Class A {
public $property;
public function __construct( $prop ) {
$this->property = $prop;
print 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' );
(I mean you can access (print,...) the property this way, but the constructor will return an object anyway.)
Upvotes: 1