3
In another 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 trouble with the ::
- Operator of scope resolution.
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 the T_PAAMAYIM_NEKUDOTAYIM
normally.
$stack = new Stack;
$stack::overflow();
However, in the case below, I can no longer do that:
$object = new stdClass;
$object->stack = $stack = new Stack;
$object->stack::overflow();
For it creates 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 a simpler way to do this in PHP (without having to resort to methods or copies of variables)?
What is the purpose of this is to accomplish something specific or just curiosity? my suggestion is to create a new method in
Stack
to make the call tooverflow()
, something like:public function auxiliar(){ echo self::overflow; }
– rray
I already have the answer to this question, @rray. As I always do, I ask things that I penetrated to learn (to help the community)
– Wallace Maxters
Actually, just do that
$object->stack->overflow()
. Static methods are accessed as common methods when you instantiate a class :)– Wallace Maxters