<?php
class Stat
{
public $var1='H';
public static $staticVar = 'Static var';
static function check()
{
echo $this->var1;
echo "<br />".self::$staticVar ."<br />";
self::$staticVar = 'Changed Static';
echo self::$staticVar."<br />";
}
function check2()
{
Stat::check();
echo $this->var1;
echo "b";
}
}
?>
Can i use it like this
$a = new Stat();
$a->check2();
A static method can only access static data members and static methods of another class or same class but cannot access non-static methods and variables. Also, a static method can rewrite the values of any static data member.
In PHP 5, calling non-static methods statically generates an E_STRICT warning. In PHP 7, calling non-static methods statically is deprecated, and will generate an E_DEPRECATED warning. See Static methods (php.net) for details. In the following example, the method foo() is called as dynamic while actually it is static.
Yes, a static method can access a non-static variable. This is done by creating an object to the class and accessing the variable through the object.
Explanation: A static function is a special type of function which is used to access only static data, any other normal data cannot be accessed through static function.
No. A static method will not have access to $this
(as there is no $this
to talk about in a static context).
If you need a reference to the current object within the static method, it is not a static method. You can however access static properties and functions from a non-static method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With