Home » Php » php – Class extending itself?

php – Class extending itself?

Posted by: admin July 12, 2020 Leave a comment

Questions:

I encountered a PHP class written by a previous employee that is defined like this:

namespace SomeNamespace;

class SomeClass extends ::SomeClass
{
    private function __construct() {}

    public static function someFunction()
    {
        //Do something
    }
}

Would somebody please explain what is going on here? Is this class extending itself? I know a singleton would use a private constructor, but not sure that is what is happening here.

The actual class has to do with caching. Not sure if that helps.

How to&Answers:

I don’t think you can do this kind of thing using :: ; but it should work if you are using the namespace separator : \

I just tested with PHP PHP 5.3.5 — and using :: does indeed get me an error.

Using \, on the other hand, works just fine (see example below).

For example, being in the global namespace (outside of any specific namespace) you could define a class SomeClass :

namespace {

    class SomeClass
    {
        public function method() {
            var_dump("child: " . __METHOD__);
        }
    }


    $obj = new SomeNamespace\SomeClass();
    $obj->method();

}

And, in a specific namespace called SomeNamespace in my example, you could define a class SomeClass that would extend the class from the global namespace — which is accessible as \SomeClass :

namespace SomeNamespace {

    class SomeClass extends \SomeClass
    {
        public function method() {
            var_dump("parent: " . __METHOD__);
        }
    }

}

Sidenote : Here, I’ve use the bracketed syntax, as I’m putting the two portions of code in the same file (see Example 3 on that manual page) — but it should work just the same with several files.


Note that with the first alpha versions of PHP 5.3, the namespace separator was not \, but ::

So, if you are using PHP 5.3 alpha 1 or 2 (and maybe 3, not sure if \ has been choosen before or after alpha 3), using :: might work.

(Of course, you should not be using an alpha — especially considering that there have been stable versions of PHP 5.3 for two years now)

Answer:

If I’m remembering correctly during the development of 5.3 :: was used as the namespace separator.