PHP 基础
PHP 简介
PHP 入门
PHP 语法
PHP 变量
PHP 常量
PHP 输出和打印
PHP 数据类型
PHP 字符串
PHP 运算符
PHP If…Else
PHP Switch…Case
PHP 数组
PHP 数组排序
PHP 循环
PHP 函数
PHP 数学运算
PHP GET 和 POST
PHP 高级
PHP 日期和时间
PHP 包含文件
PHP 文件系统
PHP 解析目录
PHP 文件上传
PHP 文件下载
PHP Cookies
PHP Sessions
PHP 发送邮件
PHP 表单处理
PHP 表单验证
PHP 过滤器
PHP 错误处理
PHP 类和对象
PHP 魔术常量
PHP JSON 解析
PHP 正则表达式
PHP 异常处理
PHP 和 MySQL 数据库
PHP MySQL 简介
PHP MySQL 连接
PHP MySQL Create Database
PHP MySQL Create Table
PHP MySQL Insert
PHP MySQL Prepared
PHP MySQL Last Inserted ID
PHP MySQL Select
PHP MySQL Where
PHP MySQL Limit
PHP MySQL Order By
PHP MySQL Update
PHP MySQL Delete
PHP MySQL CRUD 应用
PHP MySQL Ajax 搜索
PHP MySQL 登录系统
PHP参考
PHP String Functions
PHP Array Functions
PHP File System Functions
PHP Date/Time Functions
PHP Calendar Functions
PHP MySQLi Functions
PHP Filters
PHP Error Levels
PHP常见问题解答
如何在 PHP 中编写注释
如何在 PHP 中删除字符串中的空格
如何在 PHP 中查找字符串中的字符数
如何在 PHP 中查找字符串中的单词数
如何在 PHP 中删除字符串中的特殊字符
如何在 PHP 中替换字符串中的一个单词
如何在 PHP 中对字符串前面追加
如何在 PHP 中对字符串后面追加
如何在 PHP 中从字符串中提取子串
如何在 PHP 中比较两个字符串
如何在 PHP 中获取当前页面的 URL
如何在 PHP 中通过连接数组值创建字符串
如何在 PHP 中将字符串拆分为数组
如何在 PHP 中合并两个字符串
如何在 PHP 中把字符串转换成小写字母
如何在 PHP 中把字符串转换成大写字母
如何在 PHP 中把字符串的第一个字母转换成大写字母
如何在 PHP 中把特殊的 HTML 实体转换回字符
如何在 PHP 中删除字符串开头的空格
如何在 PHP 中删除字符串结尾的空格
如何在 PHP 中新建一行
如何在 PHP 中查找字符串长度
如何在 PHP 中检查变量是否已设置
如何在 PHP 中检查变量是否为空
如何在 PHP 中检查变量是否为NULL
如何在 PHP 中反转字符串
如何在 PHP 中用另一个字符串替换字符串的一部分
如何在 PHP 中计算子串在字符串中出现的次数
如何在 PHP 中计算数组中的所有元素
如何在 PHP 中打印或回显数组的所有值
如何在 PHP 中显示数组的结构和值
如何在 PHP 中颠倒数组的顺序
如何在 PHP 中检查数组中是否存在值
如何在 PHP 中检查数组中是否存在键
如何在 PHP 中删除数组中的最后一个元素
如何从 PHP 数组中删除第一个元素
如何在 PHP 中为数组的开头添加元素
如何在 PHP 中为数组的末尾添加元素
如何在 PHP 中把两个或多个数组合并成一个数组
如何在 PHP 中按字母顺序对数组值排序
如何在 PHP 中删除数组中的重复值
如何在 PHP 中随机调整数组的顺序
如何在 PHP 中比较两个数组的值
如何在 PHP 中计算数组中数值的总和
如何在 PHP 中删除数组中的空值
如何在 PHP 中用数组值填充下拉列表
如何在 PHP 中获取关联数组的所有键值
如何在 PHP 中获取关联数组的所有值
如何在 PHP 中按键对关联数组排序
如何在 PHP 中按值对关联数组排序
如何在 PHP 中从数组中获取单个值
如何在 PHP 中循环浏览多维数组
如何在 PHP 中从数组中删除元素
如何在 PHP 中检查字符串是否包含特定单词
如何在 PHP 中获取当前日期和时间
如何在 PHP 中进行重定向
如何在 PHP 中删除字符串中的所有空格
如何用 PHP 获取当前年份
如何在 PHP 中将日期从 yyyy-mm-dd 转换为 dd-mm-yyyy 格式
如何在 PHP 中将字符串转换为数字
如何在 PHP 中获取数组的第一个元素
如何在 PHP 中将日期转换为时间戳
如何在 PHP 中为空数组添加元素
如何在 PHP 中把整数转换成字符串
如何用值而不是键删除 PHP 数组元素
如何在 PHP 中将键和值同时推入数组
如何使用 PHP 定期刷新页面
如何从 PHP 字符串中删除最后一个字符
如何从 PHP 脚本返回 JSON
如何让 PHP 显示错误
PHP 类和对象 - php7基础教程 - 笔下光年
网站首页
PHP 类和对象
In this tutorial you will learn how to write code in object-oriented style in PHP. ## What is Object Oriented Programming Object-Oriented Programming (OOP) is a programming model that is based on the concept of classes and objects. As opposed to procedural programming where the focus is on writing procedures or functions that perform operations on the data, in object-oriented programming the focus is on the creations of objects which contain both data and functions together. Object-oriented programming has several advantages over conventional or procedural style of programming. The most important ones are listed below: - It provides a clear modular structure for the programs. - It helps you adhere to the "don't repeat yourself" (DRY) principle, and thus make your code much easier to maintain, modify and debug. - It makes it possible to create more complicated behavior with less code and shorter development time and high degree of reusability. The following sections will describe how classes and objects work in PHP. <div class="callout callout-success mb-3">Tip: The idea behind Don't Repeat Yourself (DRY) principle is reducing the repetition of code by abstracting out the code that are common for the application and placing them at a single place and reuse them instead of repeating it.</div> ## Understanding Classes and Objects Classes and objects are the two main aspects of object-oriented programming. A class is a self-contained, independent collection of variables and functions which work together to perform one or more specific tasks, while objects are individual instances of a class. A class acts as a template or blueprint from which lots of individual objects can be created. When individual objects are created, they inherit the same generic properties and behaviors, although each object may have different values for certain properties. For example, think of a class as a blueprint for a house. The blueprint itself is not a house, but is a detailed plan of the house. While, an object is like an actual house built according to that blueprint. We can build several identical houses from the same blueprint, but each house may have different paints, interiors and families inside, as shown in the illustration below.  A class can be declared using the `class` keyword, followed by the name of the class and a pair of curly braces (`{}`), as shown in the following example. Let's create a PHP file named Rectangle.php and put the following example code inside it so that our class code should be separated from rest of the program. We can then use it wherever it's needed by simply including the Rectangle.php file. ```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. <div class="callout callout-info mb-3">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).</div> 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 ?> ``` As you can see in the above example, calling the `getArea()` method on different objects causes that method to operate on a different set of data. Each object instance is completely independent, with its own properties and methods, and thus can be manipulated independently, even if they're of the same class. ## 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: ``` 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: ``` The class "MyClass" was initiated! The class "MyClass" was destroyed. The end of the file is reached. ``` <div class="callout callout-success mb-3">Tip: PHP automatically clean up all resources allocated during execution when the script is finished, e.g. closing database connections, destroying objects, etc.</div> <div class="callout callout-info mb-3">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.</div> ## 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. <div class="callout callout-success mb-3">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.</div> ## 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 In addition to the visibility, properties and methods can also be declared as `static`, which makes them accessible without needing an instantiation of the class. Static properties and methods can be accessed using the scope resolution operator (`::`), like this: `ClassName::$property` and `ClassName::method()`. A property declared as static cannot be accessed via the object of that class though a static method can be, 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`). <div class="callout callout-info mb-3">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.</div> 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.
上一篇:
PHP 错误处理
下一篇:
PHP 魔术常量