4

I am a junior PHP programmer. I still have a lot to learn. That's why I ask this question. In a class you have a public function which you can call it from outside that class. Sometimes you have a private function which you can call several times in that class where the private function resides, for reusable purpose. I like to set the private function to static and I call that function with:

self::privateFunctionName();

By using self it reminds me that this private function resides in that class. if I use $this->privateFunctionName() for non-static function, it could be in the superclass/base class or in that subclass itself. That is why I like to use static private function. In a professional point of view, is it a good idea to use static private function instead of non-static? Is there any disadvantage that a professional programmer like you prefers to avoid the static function?

O Connor
  • 4,236
  • 15
  • 50
  • 91
  • 1
    A private method can not be in the parent. So why do you need to be reminded in which class the method actually is? Can you outline this a little? – hakre Oct 09 '14 at 13:20

3 Answers3

3

Only using self::... must not mean the method is static. parent:: and self:: work as well for non-static methods. You can find this in the PHP manual - Scope Resolution Operator (::) and I add some exemplary code excerpt at the end of the answer.

You perhaps might want to read through all answers of this earlier question:

In total you will get there more details then my short description in this answer.

You might have been confused by the scope-resolution-operator :: which is used by those. I had a similar understanding problem grasping that.

However, do not just choose to use static methods for such a limited reason. Those static class methods should only be used in very limited and narrowed situations. As a rule of thumb:

"Do not use static class methods."

If you like to start with object oriented programming, just use normal object methods.

Here is an excerpt from existing code that shows that self:: as well as parent:: are used with standard (non-static) methods:

<?php

...

/**
 * Class XMLElementIterator
 *
 * Iterate over XMLReader element nodes
 */
class XMLElementIterator extends XMLReaderIterator
{
    private $index;
    private $name;
    private $didRewind;

    /**
     * @param XMLReader   $reader
     * @param null|string $name element name, leave empty or use '*' for all elements
     */
    public function __construct(XMLReader $reader, $name = null)
    {
        parent::__construct($reader);
        $this->setName($name);
    }

    /**
     * @return void
     */
    public function rewind()
    {
        parent::rewind();
        $this->ensureCurrentElementState();
        $this->didRewind = true;
        $this->index     = 0;
    }

    /**
     * @return XMLReaderNode|null
     */
    public function current()
    {
        $this->didRewind || self::rewind();

        $this->ensureCurrentElementState();

        return self::valid() ? new XMLReaderNode($this->reader) : null;
    }

    ...
Community
  • 1
  • 1
hakre
  • 193,403
  • 52
  • 435
  • 836
1

self:: does not in fact mean that the method is part of the same class, it may as well have been inherited from a parent class!

You should not use the semantics of static method calls to differentiate "internal" and "external" methods. There's no real point to it anyway, and you're just abusing language features for something they weren't meant for. Maybe let that be a primary lesson: don't try to invent clever new ways of using language features. Just don't.

You should view methods as small, self contained black boxes. You don't need to know and don't want to know what they do. All you know is that when you call method foo with parameter $bar, x will happen or it will return y. You don't care how this happens, just that it does because that's what the method is supposed to do.

As such, static and non-static methods convey a different use with different limitations. static methods are supposed to be called when you don't have an object, for example as alternative constructor methods (e.g. DateTime::createFromFormat).

Further, restricting a method to being static means it has no access to object instance data, which may limit you in the future. As your project evolves, you may find that your method now needs to take into account some additional data from the object to do its job. If you declared it as non-static from the beginning, all it takes is a little modification to the method itself; to the outside world it still does its job the same way (input → output). However, if you declared it as static and suddenly find yourself needing to make it non-static, you have to change a lot more code than just that one method.

Bottom line: if your method is not supposed to be exposed publicly because it's nobody's business to call it except for your own class, make it private. If the method needs to be static because it must work without object context, make it static. If it fulfils both requirements, make it private static. Otherwise, don't.

deceze
  • 510,633
  • 85
  • 743
  • 889
  • 1
    "don't try to invent clever new ways of using language features. Just don't." Amen. – thpl Oct 09 '14 at 13:18
0

Well basically a "private static" function is a construct which is totally nonsense because it cannot be called from the outside.

There is no real difference between $this-> and using self:: expect the fact that it can be called from the outside without a object and its the same amount of work for the CPU to call the function, no matter in what namespace/class this function is located.

However the fact that a private function can only be called within the same class you always have an object and the "static" modifier is somewhat superflous here because it makes no difference.

In this cases I always like to say: do what you like its just a matter of your personal style but dont switch arround, keep it that way to develop and use the standard you feel comfortable with.

In some cases there is just "another" way and a "professional" way does not exist at all. The trend often makes the one or the other method to become popular over time.

Steini
  • 2,753
  • 15
  • 24
  • 1
    Eeeeerrr.... And what if I am want to call this private function from a public static function? For example, if i have a public static function getUserDetails(), and a private static function getDetailsFromDatabase (). I can imagine some case, where private static function has reason to be there. – vaso123 Oct 09 '14 at 12:41
  • Ok this could be possible but I never ever encountered a case where this was really nesessary and im in PHP for pretty many years. But when the heck do you nest static functions to call each other? They are static because they are called from the outside if they are ment to be called from the inside they will probably not be static or your code-design is rather bad because by calling the other function you somewhat "bypass" the behaviour that private should add here. I would not suggest that pattern. – Steini Oct 09 '14 at 12:45
  • Yes, it is. Let's say, i have a class User; (i know, this design is bad for this, but just for the example). I can define a public static function getUserDetails($userId); so, from everywhere, everyone can call the User::getUserDetails($userId). Maybe, in my User class, i need to call the private static function getUserDetailsFromDatabase($userId); from multiple public static functions (in the same class). In this case, i can declare the private function as static. Because both functions are in the same class, public is accessible from anywhere, while private is only from it's own. – vaso123 Oct 09 '14 at 12:50
  • Its just a workarround to write User::getUserDetails($userId) against a clear $user = new User($userId); $user->getUserDetails(); -> This is a comparisation between procedural programming and OOP and I would definetly prefer the last one. Both ways are always possible but I cannot find any real advantage on this method... – Steini Oct 09 '14 at 12:54
  • 1
    "I would not suggest that pattern." Yeah, me neither. But static is not static because it can be called from outside, (that is public), but static is static because that is a class variable, rather then an object variable. – vaso123 Oct 09 '14 at 12:54
  • I personally love the singleton pattern which makes that obsolete because you always have an object and still dont waste memory for new objects. Atleast where the class does not directly reflect the database... Howeveer I dont say you are not right but I think its in the end a matter of taste which method you want to use. Both is possible I just told my opinion to that it looks like a workarround against OOP. – Steini Oct 09 '14 at 12:55
  • Sometimes there are classes eg. helper classes, what contains only static functions, and no need to instatntiate them. Anyway, i am not saying, this is a good pattern, i just tried to answer to the OP question. – vaso123 Oct 09 '14 at 12:56
  • Yea okay lets agree its for helper classes such as a Tools class a method you can use. – Steini Oct 09 '14 at 12:58
  • ```private static``` is not nonsense at all,- using it you can implement singleton pattern easily. – Agnius Vasiliauskas Jan 10 '23 at 14:50
  • That is still no "reason of existance" I implement singleton pattern using public static function getInstance() { } and the construct is simply private __construct() { } and private__clone() { } but there is absolutely no need for a private static function. Ofcourse you can use it but if its not required it has no real advantage. But no nee – Steini Jan 22 '23 at 22:41