Static methods in PHP

前端 未结 6 749
走了就别回头了
走了就别回头了 2020-12-15 04:38

Why in PHP you can access static method via instance of some class but not only via type name?

UPDATE: I\'m .net developer but i work with php developers too. Recent

6条回答
  •  长情又很酷
    2020-12-15 05:19

    Sometimes, it is useful if we can access methods and properties in the context of a class rather than an object. To do this, you can use static keyword. So we can access static method using class name along with scope resolution .

    class User
    {
        public static $name = 'john';
    
        public static function display()
        {
            return self::$name;
        }
    }
    
    echo User::display();
    

    Look here we declared a static method in our User class . So if we declare a static method then we can access there using just class name . No need to create object to access there . Hope you will understand all the procedure .

    Note : This is actually the main difference with a normal method : $this is not available in such methods.

    read full article from here How to Use Static Properties in PHP ?

提交回复
热议问题