nkuhta
nkuhta

Reputation: 11128

PHP:: How to call static method (or property) from extended class?

I have Model class, and Model_Something class. Model_Something have static property ( table name ).

I want to access Model_Something static property from Model class. But it try to find it in Model class and give me exception:

ErrorException [ Fatal Error ]: 
Access to undeclared static property: Model::$_collection_name

I try to access it in this way:

self::$some_property;

How to get it?

Upvotes: 0

Views: 985

Answers (2)

deceze
deceze

Reputation: 522032

You should not access a property in a class which does not exist and depend on it being present in the child. The parent cannot/should not know what a child does, it needs to be the other way around. So first, declare the property in the parent as well, so the parent can access it in any case. The child may then override the value of the property. To make sure you're always accessing the property of the executing class, you need late static binding, which you get by using static instead of self:

static::$some_property; 

http://php.net/manual/en/language.oop5.late-static-bindings.php

Upvotes: 3

ARIF MAHMUD RANA
ARIF MAHMUD RANA

Reputation: 5166

parent::$some_property; it will make your code less dependable as if you change your class name you have to change here also if you use class name.

Upvotes: -1

Related Questions