Syntax error when trying to access static method on object stored in property!

3

In another one of my tests, I noticed that in PHP there is a problem when trying to access the static method of a class, when that class is instantiated in a property of another class;

More specifically, I'm having problem with :: - Scope resolution operator.

This is the Example class:

class Stack
{

    public $overflow;

    public static function overflow()
    {
       return 'overflow';
    }
}

In the case below, I can access the static method through T_PAAMAYIM_NEKUDOTAYIM normally.

$stack = new Stack;

$stack::overflow();

However, in the case below, I can no longer do this:

$object = new stdClass;

$object->stack = $stack = new Stack;

$object->stack::overflow();

Because it generates the error:

  

Parse error: syntax error, unexpected '::' (T_PAAMAYIM_NEKUDOTAYIM)

I would not like to do something like the examples below:

$object = new stdClass;

$object->stack = $stack = new Stack;

// Copia para aceitar a sintaxe

$stack = $object->stack;

$stack::overflow();

// usa uma função para chamar o método estático   
forward_static_call($object->stack, 'overflow');

Is there any simpler way to do this in PHP (without having to resort to methods or copies of variables)?

    
asked by anonymous 30.07.2015 / 17:58

2 answers

2

In fact, the solution to this problem is simpler than it sounds.

Contrary to popular belief, static methods are not only accessible through the "double colon" :: . When it comes to properties that contain a class instance, we can access the static methods of the class instantiated with the "object separator" -> .

See:

$object = new stdClass;
$object->stack = new Stack;
$object->stack->overflow();
    
12.09.2015 / 18:29
5

This happens because the PHP interpreter has some inconsistencies and does not support some semantic combinations.

Fortunately these inconsistencies have been fixed in PHP 7 , as you can see in this example . Some other combinations that have been fixed include:

// support missing combinations of operations
$foo()['bar']()
[$obj1, $obj2][0]->prop
getStr(){0}

// support nested ::
$foo['bar']::$baz
$foo::$bar::$baz
$foo->bar()::baz()

// support nested ()
foo()()
$foo->bar()()
Foo::bar()()
$foo()()

// support operations on arbitrary (...) expressions
(...)['foo']
(...)->foo
(...)->foo()
(...)::$foo
(...)::foo()
(...)()

// two more practical examples for the last point
(function() { ... })()
($obj->closure)()

// support all operations on dereferencable scalars (not very useful)
"string"->toLower()
[$obj, 'method']()
'Foo'::$bar

Font

    
30.07.2015 / 18:37