Reputation: 2541
Say I have a class
class person {
public static function get_pk(){
return self::$primary_key;
}
}
and an extended class
class user extends person {
protected $primary_key = 'id';
}
and I want to run:
echo user::get_pk(); // should echo id
Whenever I run this it fails naturally since $primary_key is not a static variable. How do I get it to return the primary key?
Yes, I can change the class structure, function structure and make it non-static, but for all intents and purposes assume the only thing we can change is the content of the static function get_pk
Upvotes: 2
Views: 106
Reputation: 13026
The only way I can see this done is by declaring the $primary_key variable in the parent class and then assigning a value to it outside of the child class definition scope. (Notice, I've added abstract
operators to indicate that the classes are static and capitalized the first letters of the class names to follow the convention.)
<?
abstract class Person {
public static $primary_key;
public static function get_pk() {
return self::$primary_key;
}
}
abstract class User extends Person {
}
User::$primary_key = 'id';
echo User::get_pk();
/* End of file */
UPDATE
Aram, if you want the $primary_key to stay non-static then the method will need to be non-static as well as "the pseudo-variable $this is not available inside the method declared as static" as per the Static Keyword manual.
Alternatively you could convert your code to use instantiated class objects:
<?
class Person {
public function get_pk() {
return $this->primary_key;
}
}
class User extends Person {
protected $primary_key = 'id';
}
$user = new User();
echo $user->get_pk();
/* End of file */
Upvotes: 1
Reputation: 522626
You cannot access non-static properties from static
methods, since for the properties to be created the class needs to be instantiated. You can introspect the class to get values of its definition though:
public static function get_pk() {
$class = new ReflectionClass(get_called_class());
$props = $class->getDefaultProperties();
return $props['primary_key'];
}
But really, this is pretty messy and I would not recommend this for production use. Structure your classes properly to be either static
or not static
.
Upvotes: 1
Reputation: 60037
Static variables/methods relate to the class i.e. does not require an object to be created. Your primary_key
variable is created for each object. So the static method is unable to access it because the static method has no notion of a particular object and therefore does not know anything about the primary_key
. Static methods do not have the variable $this
(hence self
) defined.
I guess your best bet is to review static keyword.
Upvotes: 0