Loading... In this tutorial you will learn how to write code in object-oriented style in PHP. ## What is Object Oriented Programming 面向对象编程(OOP)是一种基于类和对象概念的编程模型。与过程编程相反,过程编程的重点是编写对数据执行操作的过程或函数,而面向对象编程的重点是创建同时包含数据和函数的对象。 与传统的或过程式的编程风格相比,面向对象的编程有几个优点。下面列出了最重要的几个。 * 它为程序提供了清晰的模块化结构。 * 它帮助你坚持“不要重复自己”(don 't repeat yourself, DRY)原则,从而使你的代码更容易维护、修改和调试。 * 它可以用更少的代码、更短的开发时间和更高的可重用性来创建更复杂的行为。 以下部分将描述PHP中类和对象的工作原理。 > 提示:不要重复自己(Don 't Repeat Yourself, DRY)原则背后的思想是通过将应用程序中常见的代码抽象出来,并将它们放在一个地方,重用它们,而不是重复它们,来减少代码重复。 ## 理解类和对象 类和对象是面向对象编程的两个主要方面。类是自包含的、独立的变量和函数的集合,它们一起工作来执行一项或多项特定任务,而对象是类的单个实例。 类就像一个模板或蓝图,可以从中创建许多单独的对象。创建单个对象时,它们继承相同的通用属性和行为,尽管每个对象的某些属性可能有不同的值。 例如,把一个类想象成一栋房子的蓝图。蓝图本身不是房子,而是房子的详细平面图。而一个物体就像一个根据蓝图建造的实际房子。我们可以用相同的蓝图建造几个相同的房子,但每个房子可能有不同的油漆,室内和家庭,如下图所示。 ![类对象关系图解](http://www.bixiaguangnian.com/uploads/images/20240508/1ca2a03c0d8c209926e16e3fa66275e4.png https://www.huangshuxiu.com/usr/uploads/2024/09/1517325843.png) 可以使用class关键字,后跟类名和一对大括号({})来声明类,如下面的例子所示。 让我们创建一个名为Rectangle.php的PHP文件,并将以下示例代码放在其中,以便将我们的类代码与程序的其余部分分离。然后我们可以在任何需要的地方使用它,只需包含Rectangle.php文件。 ```php <?php class Rectangle { // Declare properties public $length = 0; public $width = 0; // Method to get the perimeter public function getPerimeter(){ return (2 * ($this->length + $this->width)); } // Method to get the area public function getArea(){ return ($this->length * $this->width); } } ?> ``` The public keyword before the properties and methods in the example above, is an access modifier, which indicates that this property or method is accessible from anywhere. We will learn more about this a little later in this chapter. > Note: Syntactically, variables within a class are called properties, whereas functions are called methods. Also class names conventionally are written in PascalCase i.e. each concatenated word starts with an uppercase letter (e.g. MyClass). Once a class has been defined, objects can be created from the class with the new keyword. Class methods and properties can directly be accessed through this object instance. Create another PHP file name test.php and put the following code inside it. ```php <?php // Include class definition require "Rectangle.php"; // Create a new object from Rectangle class $obj = new Rectangle; // Get the object properties values echo $obj->length; // 0utput: 0 echo $obj->width; // 0utput: 0 // Set object properties values $obj->length = 30; $obj->width = 20; // Read the object properties values again to show the change echo $obj->length; // 0utput: 30 echo $obj->width; // 0utput: 20 // Call the object methods echo $obj->getPerimeter(); // 0utput: 100 echo $obj->getArea(); // Output: 600 ?> ``` The arrow symbol (->) is an OOP construct that is used to access contained properties and methods of a given object. Whereas, the pseudo-variable \$this provides a reference to the calling object i.e. the object to which the method belongs. The real power of object oriented programming becomes evident when using multiple instances of the same class, as shown in the following example: ```php <?php // Include class definition require "Rectangle.php"; // Create multiple objects from the Rectangle class $obj1 = new Rectangle; $obj2 = new Rectangle; // Call the methods of both the objects echo $obj1->getArea(); // Output: 0 echo $obj2->getArea(); // Output: 0 // Set $obj1 properties values $obj1->length = 30; $obj1->width = 20; // Set $obj2 properties values $obj2->length = 35; $obj2->width = 50; // Call the methods of both the objects again echo $obj1->getArea(); // Output: 600 echo $obj2->getArea(); // Output: 1750 ?> ``` 正如你在上面的例子中看到的,在不同的对象上调用getArea()方法会导致该方法对不同的数据集进行操作。每个对象实例都是完全独立的,都有自己的属性和方法,因此可以独立地操作它们,即使它们属于同一个类。 ## Using Constructors and Destructors To make the object-oriented programming easier, PHP provides some magic methods that are executed automatically when certain actions occur within an object. For example, the magic method \_\_construct() (known as constructor) is executed automatically whenever a new object is created. Similarly, the magic method \_\_destruct() (known as destructor) is executed automatically when the object is destroyed. A destructor function cleans up any resources allocated to an object once the object is destroyed. ```php <?php class MyClass { // Constructor public function __construct(){ echo 'The class "' . __CLASS__ . '" was initiated!<br>'; } // Destructor public function __destruct(){ echo 'The class "' . __CLASS__ . '" was destroyed.<br>'; } } // Create a new object $obj = new MyClass; // Output a message at the end of the file echo "The end of the file is reached."; ?> ``` The PHP code in the above example will produce the following output: ```php The class "MyClass" was initiated! The end of the file is reached. The class "MyClass" was destroyed. ``` A destructor is called automatically when a scripts ends. However, to explicitly trigger the destructor, you can destroy the object using the PHP unset() function, as follow: ```php <?php class MyClass { // Constructor public function __construct(){ echo 'The class "' . __CLASS__ . '" was initiated!<br>'; } // Destructor public function __destruct(){ echo 'The class "' . __CLASS__ . '" was destroyed.<br>'; } } // Create a new object $obj = new MyClass; // Destroy the object unset($obj); // Output a message at the end of the file echo "The end of the file is reached."; ?> ``` Now, the PHP code in the above example will produce the following output: ```php The class "MyClass" was initiated! The class "MyClass" was destroyed. The end of the file is reached. ``` > 提示:当脚本完成时,PHP自动清理执行期间分配的所有资源,例如关闭数据库连接,销毁对象等。 > Note:The CLASS is a [magic constant](http://www.bixiaguangnian.com/manual/php7/3995.html "magic constant") which contains the name of the class in which it is occur. It is empty, if it occurs outside of the class. ## Extending Classes through Inheritance Classes can inherit the properties and methods of another class using the extends keyword. This process of extensibility is called inheritance. It is probably the most powerful reason behind using the object-oriented programming model. ```php <?php // Include class definition require "Rectangle.php"; // Define a new class based on an existing class class Square extends Rectangle { // Method to test if the rectangle is also a square public function isSquare() { if($this->length == $this->width){ return true; // Square } else { return false; // Not a square } } } // Create a new object from Square class $obj = new Square; // Set object properties values $obj->length = 20; $obj->width = 20; // Call the object methods if($obj->isSquare()) { echo "The area of the square is "; } else { echo "The area of the rectangle is "; }; echo $obj->getArea(); ?> ``` The PHP code in the above example will produce the following output: ```php The area of the square is 400 ``` As you can see in the above example, even though the class definition of Square doesn’t explicitly contain getArea() method nor the \$length and \$width property, instances of the Square class can use them, as they inherited from the parent Rectangle class. > Tip: Since a child class is derived from a parent class, it is also referred to as a derived class, and its parent is called the base class. ## Controlling the Visibility of Properties and Methods When working with classes, you can even restrict access to its properties and methods using the visibility keywords for greater control. There are three visibility keywords (from most visible to least visible): public, protected, private, which determines how and from where properties and methods can be accessed and modified. * public — A public property or method can be accessed anywhere, from within the class and outside. This is the default visibility for all class members in PHP. * protected — A protected property or method can only be accessed from within the class itself or in child or inherited classes i.e. classes that extends that class. * private — A private property or method is accessible only from within the class that defines it. Even child or inherited classes cannot access private properties or methods. The following example will show you how this visibility actually works: ```php <?php // Class definition class Automobile { // Declare properties public $fuel; protected $engine; private $transmission; } class Car extends Automobile { // Constructor public function __construct(){ echo 'The class "' . __CLASS__ . '" was initiated!<br>'; } } // Create an object from Automobile class $automobile = new Automobile; // Attempt to set $automobile object properties $automobile->fuel = 'Petrol'; // ok $automobile->engine = '1500 cc'; // fatal error $automobile->transmission = 'Manual'; // fatal error // Create an object from Car class $car = new Car; // Attempt to set $car object properties $car->fuel = 'Diesel'; // ok $car->engine = '2200 cc'; // fatal error $car->transmission = 'Automatic'; // undefined ?> ``` ## Static Properties and Methods 除了可见性,属性和方法也可以被声明为static,这样就可以在不需要实例化类的情况下访问它们。静态属性和方法可以通过作用域解析操作符(::)来访问,比如ClassName::\$property和ClassName::method()。 声明为static的Properties不能通过该类的对象访问,但a static method可以, as demonstrated in the following example: ```php <?php // Class definition class HelloClass { // Declare a static property public static $greeting = "Hello World!"; // Declare a static method public static function sayHello(){ echo self::$greeting; } } // Attempt to access static property and method directly echo HelloClass::$greeting; // Output: Hello World! HelloClass::sayHello(); // Output: Hello World! // Attempt to access static property and method via object $hello = new HelloClass; echo $hello->greeting; // Strict Warning $hello->sayHello(); // Output: Hello World! ?> ``` The keyword self in the above example means the current class. It is never preceded by a dollar sign (\$) and always followed by the :: operator (e.g. self::\$name). The self keyword is different from the this keyword which means “the current object” or “the current instance of a class”. The this keyword is always preceded by a dollar sign (\$) and followed by the -> operator (e.g. \$this->name). > Note: Since static methods can be called without an instance of a class (i.e. object), the pseudo-variable \$this is not available inside the method declared as static. We hope you’ve understood the basic concepts of object-oriented programming by now. You’ll find more examples on OOP in PHP and MySQL database section. Last modification:September 12, 2024 © Allow specification reprint Like 如果觉得我的文章对你有用,请随意赞赏