Does static method in PHP have any difference with non-static method?

前端 未结 6 868
我寻月下人不归
我寻月下人不归 2020-12-03 08:21
class t {
    public function tt()
    {
        echo 1;
    }
}
t::tt();

See?The non-static function can also be called at class level.So what\'s

6条回答
  •  情歌与酒
    2020-12-03 08:59

    In general a static method is also called class method while a non-static method is also called object method or instance method.

    The difference between a class method and an object method is that class methods can only access class properties (static properties) while object methods are used to access object properties (properties of the very same class instance).

    Static methods and properties are used to share common data over or for all instances of that specific class.

    You could, for example, use a static property to keep track of the number of instances:

    class A {
        private static $counter = 0;
    
        public function __construct() {
            self::counter = self::counter + 1;
        }
    
        public function __destruct() {
            self::counter = self::counter - 1;
        }
    
        public static function printCounter() {
            echo "There are currently ".self::counter." instances of ".__CLASS__;
        }
    }
    
    $a1 = new A();
    $a2 = new A();
    A::printCounter();
    unset($a2);
    A::printCounter();
    

    Note that the static property counter is private so it can only be accessed by the class itself and instances of that class but not from outside.

提交回复
热议问题