Can static function access non-static variables in php?

user1983198 picture user1983198 · Jan 16, 2013 · Viewed 15k times · Source
<?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();

Answer

MatsLindh picture MatsLindh · Jan 16, 2013

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.