Home > Backend Development > PHP Tutorial > Detailed explanation of the difference between php static methods and ordinary methods

Detailed explanation of the difference between php static methods and ordinary methods

怪我咯
Release: 2023-03-12 17:52:01
Original
1691 people have browsed it

The following editor will bring you a detailed discussion of the difference between phpstatic methods and ordinary methods. The editor thinks it is quite good, so I will share it with you now and give it as a reference for everyone. Let’s follow the editor and take a look.

is as follows:

<?php 
header(&#39;content-type:text/html;charset=utf-8&#39;); 
/* 
普通方法,存放类内,只有一份

静态方法,也是存放于类内,只有一份

区别在于:普通方法需要对象去调用,需要绑定$this 
即,普通方法,必须要有对象,然后让对象来调用 

而静态方法,不属于哪一个对象,因此不需要绑定$this 
即,不需要对象也可以调用 
*/

class Human{ 
  static public $head=1; 
  public function easyeat(){ 
    echo &#39;普通方法吃饭<br />&#39;; 
  } 
  static public function eat(){ 
    echo &#39;静态方法吃饭<br />&#39;; 
  } 
  public function intro(){ 
    echo $this->name; 
  } 
} 
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();

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

/* 
总结: 
类》访问->静态方法(类的方法)->可以 
类》访问->普通方法(对象的方法)->不可以(虽然方法里不用$this关键字时,可以!但不支持这种写法)

对象》访问》静态方法(类的方法)->可以 
对象》访问》普通方法(对象的方法)->可以

*/ 
?>
Copy after login

The above is the detailed content of Detailed explanation of the difference between php static methods and ordinary methods. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template