PHP Classes: Usage, Syntax & Examples
In PHP, a class is used to define a collection of attributes and methods for an object. Classes allow for the creation of multiple objects with the same properties and methods. The basic syntax for a class is as follows:
class ClassName {
// 属性
public $property1;
protected $property2;
private $property3;
// 方法
public function method1() {
// 方法的实现
}
protected function method2() {
// 方法的实现
}
private function method3() {
// 方法的实现
}
}
In a class, it is possible to define public, protected, and private properties and methods. Public properties and methods can be accessed by instances of the class as well as externally, whereas protected properties and methods can only be accessed within the class and its subclasses, and private properties and methods can only be accessed within the class itself.
When using a class, the first step is to instantiate an object, and then access the class’s properties and methods through that object.
$obj = new ClassName();
$obj->property1 = 'value';
$obj->method1();
Class can also utilize constructor and destructor methods to initialize objects and clean up resources.
class ClassName {
public function __construct() {
// 构造方法
}
public function __destruct() {
// 析构方法
}
}
The constructor method is automatically called when an object is instantiated, while the destructor method is automatically called when an object is destroyed. In PHP, functionalities such as class inheritance, interface implementation, static properties, and methods can also be used.