search
HomeBackend DevelopmentPHP TutorialDetailed explanation of commonly used keywords and magic methods in PHP object-oriented

1.construct()

The instantiated object is automatically called. Construct is called when construct and the function with the class name and function name exist at the same time, and the other one is not called.

The function with the class name and function name is the old version of the constructor.

2.destruct()

is called when deleting an object or when an object operation ends.

3.call()

The object calls a method. If the method does not exist, call this method

4.get()

Read an object property. If the object property is private, it will be called

5. set()

When assigning a value to an object property, it will be called if the property is private

6.toString()

It will be called when printing an object.

7.clone()

Called when cloning an object, such as: $a=new test(); $a1=clone $a;

8.sleep( )

Serialize was called before. If the object is larger than and you want to delete something during serialization, you can use it.

9.wakeup()

is called when Unserialize is used to do some object initialization work.

10.isset()

Detects whether an object's attributes exist. If the detected attribute is private, it will be called.

11.unset()

When deleting an object attribute, if the deleted object attribute is private, it will be called

12.set_state()

Called when var_export is called. Use the return value of set_state as the return value of var_export.

13.autoload()

When instantiating an object, if the corresponding class does not exist, this method will be used.


The following editor will bring you a detailed discussion of PHP object-orientedcommonly used keywords and magic methods. The editor thinks it’s pretty good, so I’ll share it with you now and give it as a reference. Let’s follow the editor and take a look.

Commonly used keywords in PHP object-oriented

final

1.Final cannot modify member attributes (this keyword is not used for constants in classes)

2.Final can only modify classes and methods

Function:

Classes modified with final cannot be inherited by subclasses

Methods modified with final cannot be overridden by subclasses

Used to restrict classes from being inherited, methods If not overridden, use final

<?php
//final修饰的类不能被继承
final class Person{
  var $name;
  var $age;
  var $sex;

  function construct($name,$age,$sex){
    $this->name=$name;
    $this->age=$age;
    $this->sex=$sex;
  }

  function fun1(){
    echo $this->name;
  }
}

//Student类继承类用final修饰的Person类,所以会报错
class Student extends Person{
}

$stu=new Student("zs",20,"nan");

$stu->fun1();
?>

static (static keyword)

1. Use static to modify member properties and member methods, but not Modified class

2. Member attributes modified with static can be shared by all objects of the same class

3. Static data is stored in the data segment in memory (initializing the static segment)

4. Static data is allocated to memory when the class is loaded for the first time. When the class is used in the future, it is obtained directly from the data segment

5. What is a class being loaded? As long as this class is used in the program (this class name appears)

6. Static methods (static modified methods) cannot access non-static members (static members can be accessed in non-static methods)

Because non-static members must be accessed using objects, $this is used to access internal members. Static methods do not need to be called using objects, so there is no object. $this cannot represent objects. Non-static Members must also use objects

If you are sure that non-static members are not used in a method, you can declare this method as a static method

Note: Static members must use class names To access, don’tCreate an object, don’t use an object to access

Class name::static member

If you use static members in a class, you can use self to represent this class

const

1. It can only modify member attributes

2. Use const

# to declare constant attributes in a class ##3. The access method is the same as static member properties (use class name::constant outside the class and self::constant inside the class)

4. Constants must be given initial values ​​when they are declared.

<?php
//定义一个类“人们”
class Person{
  protected $name;
  protected $age;
  protected $sex;
  static $country="中国";
  //声明一个常量
  const RUN="走";

  //构造方法
  function construct($name,$age,$sex){
    $this->name=$name;
    $this->age=$age;
    $this->sex=$sex;
  }

  function getCountry(){
    //如果在类中使用静态成员,可以使用self代表本类
    return self::$country;
  }

  function say(){
    echo "我的名字:{$this->name},我的年龄:{$this->age},我的性别:{$this->sex}。<br>";
  }

  protected function eat(){
    echo "吃饭!<br>";
  }

  function run(){
    //在类的内部使用常量 self::常量
    echo self::RUN."<br>";
  }

  //声明静态的方法
  static function hello(){
    echo "你好<br>";
  }
}

Magic methods commonly used in PHP object-oriented

call()

Function: When calling a method that does not exist in the object, a system error will appear, and then the program will exit.

When to call automatically: It will be called automatically when calling a method that does not exist in an object

Handle some non-existent error calls

This method requires two Parameters

<?php
//定义一个类“人们”
class Person{
  protected $name;
  protected $age;
  protected $sex;
  static $country="中国";
  //声明一个常量
  const RUN="走";

  //构造方法
  function construct($name,$age,$sex){
    $this->name=$name;
    $this->age=$age;
    $this->sex=$sex;
  }

  function getCountry(){
    //如果在类中使用静态成员,可以使用self代表本类
    return self::$country;
  }

  function say(){
    echo "我的名字:{$this->name},我的年龄:{$this->age},我的性别:{$this->sex}。<br>";
  }

  protected function eat(){
    echo "吃饭!<br>";
  }

  function run(){
    //在类的内部使用常量 self::常量
    echo self::RUN."<br>";
  }

  //处理一些不存在的错误调用
  //就会在调用一个对象中不存在的方法时就会自动调用
  function call($methodName,$args){
    //$methodName调用不存在方法的方法名 $args里面的参数
    echo "你调用的方法{$methodName}(参数:";
    print_r($args);
    echo ")不存在<br>";
  }

  //声明静态的方法
  static function hello(){
    echo "你好<br>";
  }
}

$p=new Person("张三",20,"女");

$p->test(10,20,30);
$p->demo("aa","bb");
$p->say();
?>

toString()

is automatically called when directly outputting an object reference. It is the fastest way to quickly obtain a string representation. Method

<?php
//定义一个类“人们”
class Person{
  protected $name;
  protected $age;
  protected $sex;
  static $country="中国";
  //声明一个常量
  const RUN="走";

  //构造方法
  function construct($name,$age,$sex){
    $this->name=$name;
    $this->age=$age;
    $this->sex=$sex;
  }

  function say(){
    echo "我的名字:{$this->name},我的年龄:{$this->age},我的性别:{$this->sex}。<br>";
  }

  function toString(){
    return self::$country."<br>{$this->name}<br>{$this->age}<br>{$this->sex}<br>".self::RUN;
  }
}

$p=new Person("张三",21,"女");
echo $p;
?>

clone()

Clone object is processed using clone()

Original (original object)

Copy (copied object)

clone() is a method automatically called when cloning an object

As soon as an object is created, there must be an initialization action, and The constructor method constuct has similar functions

在clone()方法中的$this关键字代表的是复本的对象,$that代表原本对象

<?php
//定义一个类“人们”
class Person{
  var $name;
  protected $age;
  protected $sex;
  static $country="中国";
  //声明一个常量
  const RUN="走";

  //构造方法
  function construct($name,$age,$sex){
    $this->name=$name;
    $this->age=$age;
    $this->sex=$sex;
  }

  function say(){
    echo "我的名字:{$this->name},我的年龄:{$this->age},我的性别:{$this->sex}。<br>";
  }

  function clone(){
    $this->name="王五";
    $this->age=18;
    $this->sex="男";
  }

  function destruct(){
    echo $this->name."<br>";
  }
}

$p=new Person("张三",21,"女");
$p->say();
//这并不能叫做克隆对象,因为在析构时只析构一次
/*$p1=$p;
$p1->name="李四";
$p1->say();*/

$p1= clone $p;
$p1->say();
?>

autoload()

注意:其它的魔术方法都是在类中添加起作用,这是唯一一个不在类中添加的方法

只要在页面中使用到一个类,只要用到类名,就会自动将这个类名传给这个参数

<?php
function autoload($className){
  include "./test/".$className.".class.php";
}

  $o=new One;
  $o->fun1();  

  $t=new Two;
  $t->fun2();

  $h=new Three;
  $h->fun3();

?>

test里的文件

one.class.php

<?php
class One{
  function fun1(){
    echo "The Class One<br>";
  }
}
?>

two.class.php

<?php
class Two{
  function fun2(){
    echo "The Class Two<br>";
  }
}
?>

three.class.php

<?php
class Three{
  function fun3(){
    echo "The Class Three<br>";
  }
}
?>

对象串行化(序列化):将一个对象转为二进制串(对象是存储在内存中的,容易释放)

使用时间:

1.将对象长时间存储在数据库或文件中时

2.将对象在多个PHP文件中传输时

serialize();    参数是一个对象,返回来的就是串行化后的二进制串

unserialize();  参数就是对象的二进制串,返回来的就是新生成的对象

sleep()

是在序列化时调用的方法

作用:就是可以将一个对象部分串行化

只要这个方法中返回一个数组,数组中有几个成员属性就序列化几个成员属性,如果不加这个方法,则所有成员都被序列化

wakeup()

是在反序列化时调用的方法

也是对象重新诞生的过程

<?php
//定义一个类“人们”
class Person{
  var $name;
  protected $age;
  protected $sex;
  static $country="中国";
  //声明一个常量
  const RUN="走";

  //构造方法
  function construct($name,$age,$sex){
    $this->name=$name;
    $this->age=$age;
    $this->sex=$sex;
  }

  function say(){
    echo "我的名字:{$this->name},我的年龄:{$this->age},我的性别:{$this->sex}。<br>";
  }

  function clone(){
    $this->name="王五";
    $this->age=18;
    $this->sex="男";
  }

  //是在序列化时调用的方法,可以部分串行化对象
  function sleep(){
    return array("name","age");
  }

  //是在反序列化时调用的方法,也是对象重新诞生的过程。可以改变里面的值
  function wakeup(){
    $this->name="sanzhang";
    $this->age=$this->age+1;
  }

  function destruct(){

  }
}
?>

read.php

<?php
  require "11.php";
  
  $str=file_get_contents("mess.txt");
  $p=unserialize($str);

  echo $p->say();
?>

write.php

<?php
  require "11.php";

  $p=new Person("张三",18,"男");

  $str=serialize($p);

  file_put_contents("mess.txt",$str);
?>

The above is the detailed content of Detailed explanation of commonly used keywords and magic methods in PHP object-oriented. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft