【英文】PHP类和对象

Introduction

PHP Classes and Objects Study Notes

Creating Classes

  • Properties and methods can be defined within a class
1
2
3
4
5
6
7
8
9
<?php
class ClassName {
public $propertyName;

function methodName() {
...
}
}
?>

Creating Objects

1
2
3
<?php
$objectName = new ClassName();
?>

Assigning values to properties when creating an object

1
2
3
<?php
$objectName = new ClassName('propertyName'->propertyValue);
?>

Assigning values to properties after creating an object

1
2
3
<?php
$objectName->propertyName = propertyValue;
?>

Methods

Regular Methods

1
2
3
4
5
6
7
<?php
class ClassName {
function methodName() {
...
}
}
?>

Magic Methods

  • Magic methods are methods with special functionalities, and their method names start with __
1
2
3
4
5
6
7
<?php
class ClassName {
function __magicMethodName() {
...
}
}
?>
Magic Method Name Remarks
__construct() Automatically called when creating an object
__destruct() Automatically called when destroying an object
__call() Called when an object calls an inaccessible method
__callStatic() Called when a class calls an inaccessible static method
__get() Called when retrieving an inaccessible property in an object
__set() Called when modifying an inaccessible property in an object
__isset() Called when calling isset() or empty() on an inaccessible property in an object
__unset() Called when calling unset() on an inaccessible property in an object
__sleep() Called before executing the serialize() method
__wakeup() Called before executing the unserialize() method
__toString() Called when casting an object to a string
__invoke() Called when attempting to call an object as a function
__set_state() Called when exporting a class with the var_export() method
__clone() Called after cloning an object with the clone() method, usually used to modify the cloned object’s properties

Completed

References

Bilibili - Qianfeng Education Network Security Academy