I'm studying OOP in PHP. And I'm confused about using static methods
and properties.
In this example I will use a little cache example on server side. But
I'm not sure to use static method and property
So, how to create and use static method/properties :
class Villa extends CI_Model
{
protected static $cacheOwner = null;
public static function owner()
{
if ( ! is_null(static::$cacheOwner) ) {
return static::$cacheOwner;
}
}
}
Use it as
Villa::owner();
I think it will work but to use "static" is better? Or I must use
"static" only when inherits a property or method from a parent class?
No, it's not right at all because static considered harmful
and anti-pattern
. In the term object oriented programming
where Objects
encapsulate state and provide methods to transform this state but when you use static
properties and methods it violates the principle because it (static) preserves the same state on all instantiated objects and hence it's a class oriented programming
, not OOP
. In OOP
classes are just blueprints/data type and objects are the things that comes in to play. Also static methods/classes doesn't facilitate unit testing because of hard dependency and also hard to extend. In some cases like singleton design pattern, static class methods/properties are probably useful but it's (singleton) itself considered a bad design pattern and out of OOP
. Check SOLID and other links provided in (See also) section.
So, try to avoid static
and finally, none can tell you what actually you need in your class but you, because you know what you are going to do and how is your class related with your application and if you need to maintain the same state of a property/data all the way to your application's lifetime then you may use it but not sure. Also, check this search result and read some good answers, you'll learn a lot from here, at least I did a lot and i found this article with some examples, could be helpful too.