Home > Backend Development > PHP Problem > What is the difference between static methods and ordinary methods in php

What is the difference between static methods and ordinary methods in php

王林
Release: 2023-03-03 22:36:02
Original
3381 people have browsed it

The difference between static methods and ordinary methods in php is: ordinary methods need objects to call and $this needs to be bound, that is, ordinary methods must have objects and then let the objects be called; static methods do not belong to either Object, so there is no need to bind $this, that is, it can be called without an object.

What is the difference between static methods and ordinary methods in php

Ordinary methods are stored in the class and have only one copy; static methods are also stored in the class and have only one copy.

(Recommended tutorial: php graphic tutorial)

The difference is: ordinary methods require objects to call and $this needs to be bound, that is, ordinary methods must have object, and then let the object call it. Static methods do not belong to any object, so there is no need to bind $this, that is, they can be called without an object.

(Learning video recommendation: Introduction to Programming)

Example analysis:

<?php
header(&#39;content-type:text/html;charset=utf-8&#39;);

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();
?>
Copy after login

The above is the detailed content of What is the difference between static methods and ordinary methods in php. 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