Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP reference Class from variable with static method access

Tags:

php

class

static

Gives an Error:

$this->model::byUserPermission()

Leads to: syntax error, unexpected '::' (T_PAAMAYIM_NEKUDOTAYIM)

Works:

$facade = $this->model;
$facade::byUserPermission()

Is this a PHP Bug? Or can someone explain this to my, why that is happening (I am using php 5.6 and i am new to php. From my point of view, both are exactly the same). Thanks

like image 746
Tim Schmidt Avatar asked Sep 23 '15 20:09

Tim Schmidt


People also ask

How can we access static variable in static method in PHP?

Static properties are accessed using the Scope Resolution Operator ( :: ) and cannot be accessed through the object operator ( -> ). It's possible to reference the class using a variable. The variable's value cannot be a keyword (e.g. self , parent and static ). print $foo::$my_static .

How can use static variable in class in PHP?

The static keyword is used to declare properties and methods of a class as static. Static properties and methods can be used without creating an instance of the class. The static keyword is also used to declare variables in a function which keep their value after the function has ended.

How do you access a variable in a static method?

A static method cannot access a class's instance variables and instance methods, because a static method can be called even when no objects of the class have been instantiated. For the same reason, the this reference cannot be used in a static method.

Can we inherit static class in PHP?

PHP implements a feature called late static bindings which can be used to reference the called class in a context of static inheritance.


1 Answers

The problem is that this statement $this->model::byUserPermission() is ambiguous. And can be interpreted in multiple ways.

1) You could be trying to use the model property of the class that you are in to call a class's static method. As you are attempting in your question.

2) You could also mean you want to access the property of the class returned by the static function byUserPermission() in the model class.

like image 184
Schleis Avatar answered Oct 31 '22 00:10

Schleis