Does the class extend itself?

I came across a PHP class written by a previous collaborator, which is defined as follows:

namespace SomeNamespace; class SomeClass extends ::SomeClass { private function __construct() {} public static function someFunction() { //Do something } } 

Can someone please explain what is going on here? Is this class expanding? I know that singleton will use a private constructor, but I'm not sure if this is happening here.

The actual class is related to caching. Not sure if this helps.

+8
syntax oop php
source share
2 answers

I do not think you can do such things using :: ; but it should work if you use a namespace delimiter: \

I just tested with PHP PHP 5.3.5 - and using :: really causes me an error. Using \, on the other hand, works fine (see example below).


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

 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 can define the SomeClass class, which extends the class from the global namespace, available as \SomeClass :

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


Sidenote: here I use the copied syntax , since I put two pieces of code in the same file (see Example 3 on this page of the manual), but it should work the same with several files.



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

So, if you are using PHP 5.3 alpha 1 or 2 (and possibly 3, you are not sure if \ was selected before or after alpha 3), using :: might work.

(Of course, you should not use alpha - especially considering that for two years there have been stable versions of PHP 5.3)

+6
source share

If I remember correctly during development 5.3 :: , it was used as a namespace delimiter.

+2
source share

All Articles