The difference between php static method and ordinary method

The difference between php static method and ordinary method

<?php
header('content-type:text/html;charset=utf-8');
//普通方法,存放类内,只有一份。
//静态方法,也是存放于类内,只有一份。
//区别在于:普通方法需要对象去调用,需要绑定$this即,普通方法,必须要有对象,然后让对象来调用, 而静态方法,不属于哪一个对象,因此不需要绑定$this 即,不需要对象也可以调用

class Human{
    
    
    static public $name =  'xiaohong';
//    protected $name = 'xiaohong';

    public function easyeat(){
    
    
        echo '普通方法吃饭<br />';
    }
    static public function eat(){
    
    
        echo '静态方法吃饭<br />';
    }
    public function intro(){
    
    
        echo self::$name . PHP_EOL;
//        echo $this->name.PHP_EOL;
    }
}
Error_reporting(E_ALL|E_STRICT);
//用类的方式调用静态方法
Human::eat();
/*
以下方法easyeat是一个非静态方法,就由对象来调用,但,用类来调用此方法来也可以执行,而严格状态下,此方法会执行,同时报错,
Strict Standards: Non-static method Human::easyeat() should not be called statically in D:\application\PHPnow-1.5.6\htdocs\yan18\types\staticfun.php on line 32
*/
Human::easyeat();
/*
接上,从逻辑来理解,如果用类名静态调用非静态(普通)方法
比如:intro()
那么,这个$this是指哪个对象呢??
因此会报错,因为找不到对象!
Fatal error: Using $this when not in object context in D:\application\PHPnow-1.5.6\htdocs\yan18\types\staticfun.php on line 23
*/
Human::intro();
//  (new Human())->intro();  //可以这样调用

/*
如上分析,其实,非静态方法,是不能由类名静态调用的,但目前,php中的面向对象检测不够严格,只要静态方法中没有$this关键字,就会转化成静态方法来处理!
*/
$li = new Human();
$li->eat();

to sum up:

  1. It is possible for classes to access static methods (methods of the class).

  2. It is not possible for classes to access ordinary methods (methods of objects) (although it is possible when the $this keyword is not used in the method, this type of writing is not supported)

  3. It is possible for objects to access static methods (methods of classes).

  4. It is possible for objects to access ordinary methods (methods of objects).

Guess you like

Origin blog.csdn.net/qq_39004843/article/details/105834408