Reputation: 1558
I am trying to work out whether the private static method in the example below should be non-static. It is only concerned with the static properties of the class which leads me to believe it is okay as a static method. However, it is only invoked from a non-static method, which suggests it should be a non-static method too.
I understand when a public method should be static, but not when a private method should be static.
Thanks in advance for your advice!
<?php
class MyClass
{
private static $initialized = false;
private static $staticProperty1;
private static $staticProperty2;
private $normalProperty1;
public function __construct($normalProperty)
{
$this->normalProperty1 = $normalProperty;
}
public function doSomething()
{
self::initialize();
// Now do some other stuff
}
private static function initialize()
{
if (!self::$initialized) {
self::$staticProperty1 = 'Hello';
self::$staticProperty2 = 'World';
self::$initialized = true;
}
}
}
Upvotes: 1
Views: 948
Reputation: 1328
This is an interesting question. You want to know when a private function should be static.
It has to be static if you want to call it from another static method. That is because you do not have access to $this
.
My previous assumption was not correct. You can also call a non static method from a static function. But you have to consider that you do not have access to the object itself with the variable $this
. Also it is not possible to access non static object properties.
In your example, in my opinion if you call the method from a non static context anyway, you can make it not static. There is no need for it to be static. But I cannot tell you if this is good practice. Just what I would do.
Upvotes: 1
Reputation: 724
Usually I do private static method when I want my public static method to call another method.
Upvotes: 1