Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can static function access non-static variables in php? [closed]

<?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();
like image 985
user1983198 Avatar asked Jan 16 '13 10:01

user1983198


People also ask

Can static function access non-static variable?

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.

Can static function call non-static function PHP?

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.

Can static blocks access non-static variables?

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.

Can static member functions access non-static data members?

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.


1 Answers

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.

like image 125
MatsLindh Avatar answered Oct 04 '22 07:10

MatsLindh