Reputation: 263
Consider this example,
class A {
public function who() {
echo 'The name of the class is ' . __CLASS__;
}
}
A::who();
Output: The name of the class is A
And this,
class A {
public $vars=12;
}
echo A::$vars;
Which results in the following error,
Fatal error: Uncaught Error: Access to undeclared static property: A::$var in G:\xampp\htdocs\Learn_PHP\PHP1\name_class.php:10 Stack trace: #0 {main} thrown in G:\xampp\htdocs\Learn_PHP\PHP1\name_class.php on line 10
What is happening? Why is a public method accessible via class? And why is the same not happening with a property?
Upvotes: 1
Views: 65
Reputation: 6568
From the php.net page for Scope Resolution Operator:
The Scope Resolution Operator (also called Paamayim Nekudotayim) or in simpler terms, the double colon, is a token that allows access to static, constant, and overridden properties or methods of a class.
Your function is a method, hence the use of ::
is ok. The variable however isn't static or a constant, nor is it an overridden property of a parent class. So the use of ::
won't work for it.
full page from docs: https://secure.php.net/manual/en/language.oop5.paamayim-nekudotayim.php
Upvotes: 1
Reputation: 4385
To make the second example works as the first one just change it as follows
class A {
public static $vars=12;
}
echo A::$vars;
By adding Static to the attribute because you are calling it in a static way.
Actually PHP allows calling none static methods in a static way as of first example, but not for none static variable.
According to documentation this behavior will be changed in PHP 7
Warning In PHP 7, calling non-static methods statically is deprecated, and will generate an E_DEPRECATED warning. Support for calling non-static methods statically may be removed in the future.
Please review this URL Static keyword in PHP
Upvotes: 0