Home  >  Article  >  Backend Development  >  A brief discussion on object-oriented programming in PHP

A brief discussion on object-oriented programming in PHP

不言
不言Original
2018-04-09 15:31:4211303browse

The content of this article is about a brief discussion of PHP object-oriented programming, which has certain reference value. Friends in need can refer to it

1. Basic practice of PHP object-oriented programming

<?php
/*
*    通过对象的编程方式,可将实现生活中的一切事物以对象的形式表现出来。便于理解、维护、扩展等;
*    本示例:定义一个“人”类
*    $name : 对象中的成员属性,在此类中表示人的姓名
*    say() : 对象中的成员方法,在此类中表示人说话的方法
*    $this : PHP中的伪变量,表示自身的类
*    __construct() : php中的魔术方法,构造函数,在实例化类时自动执行
*    __destruct() : php中的魔术方法,析构函数,当类调用完成后自动执行
*/
class Human
{
    public $name;
    public $sex;
    public $age;
    public function __construct($name,$sex,$age) 
    {
        $this->name = $name;
        $this->sex = $sex;
        $this->age = $age;
    }
    public function say()
    {
        echo &#39;大家好,我的名字叫&#39;.$this->name.&#39;,今年&#39;.$this->age.&#39;岁,我的性别是&#39;.$this->sex;
    }
    public function __destruct()
    {
        $this->name = null;
        $this->sex = null;
        $this->age = null;
    }
}
//实例化“人”类
$male = new Human("张三","男","20");
//调用“人”类说话的方法
$male->say();

//输出结果:大家好,我的名字叫张三,今年20岁,我的性别是男
?>

2. Advanced PHP object-oriented programming practice

Knowledge points: class inheritance, method rewriting, access control, static keyword, final key Words, data access, interfaces, polymorphism, abstract classes

2.1. Class inheritance: extends keyword
For example: an operator, a host, they have common human behavior methods, But they all have their own different specialties. Therefore, when programming, you need to create a parent class for them and inherit it;

<?php
/*
*    创建一个“人”类做为父类,继承的子类都拥有其父类的成员属性、方法
*/
class Human
{
    public $name;
    public function say()
    {
        echo "父类说话的方法,姓名:".$this->name."\n";
    }
    public function eat()
    {
        echo "父类吃饭的方法\n";
    }
}
/*
*    创建一个“运动员”类,继承“人”类
*    extends : 关键字,继承某个类
*/
class Sport extends Human
{
    public $type;    
    public function __construct($name,$type)
    {
        $this->name = $name;    //给父类 $name 属性赋值
        $this->type = $type;    
    }
    public function run()
    {
        $this->say();   //调用父类“说话”的方法
        echo "我在正跑步,我是一员".$this->type."运动员.....\n";
    }
}
/*
*    创建一个“主持人”类,继承“人”类
*    extends : 关键字,继承某个类
*/
class Host extends Human
{
    public $television; 
    public function __construct($name,$television)
    {
        $this->name = $name;    
        $this->television= $television;   
    }
    public function perform()
    {
        $this->eat();   //调用父类“吃饭”的方法
        echo "我在正表演一个节目,我是".$this->television."电视台的一名主持人.....\n";
    }
}

//实例化“运动员”类
$nba = new Sport("乔丹","篮球");
$nba->run();

//实例化“主持人”类
$tv = new Host("张三","北京卫视");
$tv->perform();

//输出结果:
//父类说话的方法,姓名:乔丹 我在正跑步,我是一员篮球运动员..... 
//父类吃饭的方法 我在正表演一个节目,我是北京卫视电视台的一名主持人.....
?>

2.2. Method rewriting: subclasses rewrite the methods of the parent class

<?php
class Human
{
    public function say()
    {
        echo "父类说话的方法";
    }
}
class Sport extends Human
{
    //重写父类“说话”的方法
    public function say()
    {
        echo "子类说话的方法";
    }
}
$nba = new Sport();
$nba->say();
//输出结果:子类说话的方法
?>

2.3. Access control: public, protected , private keyword
public: Define public member attributes or methods, can be used anywhere
protected: Define protected member attributes or methods, only allowed to be used by the class itself or subclasses
private: Definition Private member attributes or methods are only allowed to be used by the class itself

<?php
class Human
{
    public $name;
    protected $sex;
    private $age;
    
}
//实例化对象,给公共属性赋值可正常输出结果,外部不能给protected、private受保护的成员属性赋值或使用
$worker = new Human();
$worker->name = "张三";
echo $worker->name;

?>

2.4, static (static) keyword
1), static attributes are used to save the public data of the class;
2), Only static properties or methods can be accessed in static methods, and the $this pseudo variable cannot be used;
3). Static members can be accessed and used without instantiating the object through the new keyword;

<?php
class Human
{
    static $name = "张三";
    static function say()
    {
        echo "我的姓名叫:".self::$name;
    }
}
//外部使用静态成员属性或方法
echo Human::$name;
Human::say();

//输出结果:张三  我的姓名叫:张三
?>

2.5. final keyword: member methods are not allowed to be overridden or inherited.
Example: 1. For the method "Eat" of the parent class, we do not want the subclass to rewrite it; 2. For the class "Athletes", we do not want it to be overridden. I hope it will create a subclass;

<?php
class Human
{
    final public function eat()
    {
        echo "父类吃饭的方法,不允许子类重写";
    }
}
final class Sport extends Human
{
    public function eat()
    {
        echo "子类吃饭的方法。此时程序将会报致命错误";
    }
}
//创建一个类继承 Sport 这个类。此时程序也将会报致命错误。因为 Sport 类不允许再创建子类
class Student extends Sport
{
    public $name;
}

//实例化 Sport 类 ,调用 eat() 方法
$nba = new Sport();
$nba->eat();

//实例化 Student 类 ,给 name 属性负值
$obj = new Student();
$obj->name = "张三";

//输出结果:Fatal error: Cannot override final method Human::eat() in ******.php on line 15
//Fatal error: Class Student may not inherit from final class (Sport) in ****.php on line 20
?>

2.6. Data access: $this, self, parent keyword
$this: Pseudo variable, representing the class itself, accessible to this class and the parent class Member properties and methods.
self: access static member properties or methods in the class
parent: access member properties or methods of the parent class

<?php
class Human
{
    static $name = "张三";
}
class Sport extends Human
{
    static function getParentName()
    {
        echo parent::$name;
    }
    public function get() 
    {
       self::getParentName(); 
    }
}
$obj = new Sport();
$obj->get();
//输出结果:张三
?>

2.7. Interface: define common behavior methods of different classes, but do not Specific implementation, specific methods are implemented by subclasses;
For example: people can eat, animals can also eat, and even some plants can eat, but they eat in different ways, so you need to define an interface class at this time, The specific method is implemented by subclasses;
Define the interface keyword: interface
Implement the interface method keyword: implements

<?php
//定义一个接口类,有吃饭的方法,但不具体实现。
interface ICanEat
{
    public function eat($food);
}
class Human implements ICanEat
{
    //eat()方法必须由子类来实现,否则程序将报致命错误
    public function eat($food) 
    {
        echo "I&#39;m eating ".$food;
    }
}
class Animal implements ICanEat
{
    public function eat($food)
    {
        echo "It&#39;s eating ".$food;
    }
}
//实例化一个“人”类
$people = new Human();
$people->eat(&#39;rice&#39;);

//实例化一个“动物”类
$monkey = new Animal();
$monkey->eat(&#39;banana&#39;);

//输出结果:I&#39;m eating rice
// It&#39;s eating banana

?>

2.8. Polymorphism: For example, interface A has two implementations B and C , B and C can have different implementations of the methods defined in the A interface. This phenomenon is called polymorphism;
In the above example, the ICanEat interface defines an eat() method. Humans eat rice and monkeys eat bananas. . They all implement an "eat" method, but they have different behaviors when eating, which is called polymorphism;

2.9. Abstract class: intervenes between the interface and the definition of the class, allowing part of the class to The method is not implemented, but a part of the method that has the same function and will not change is implemented. However, no implemented methods are allowed in interface classes.
For example: both humans and animals have methods for eating and breathing. Except for eating, the breathing methods are the same. In this case, an abstract class needs to be defined to implement it.
Define abstract class keywords: abstract

<?php
//定义一个抽象类,里面有吃饭和呼吸的方法。呼吸方法需要在抽象类中具体实现
abstract class ICanEat
{
    abstract function eat($food);
    public function breath()
    {
        echo &#39;Breath use the air...&#39;;
    }
}
class Human extends ICanEat
{
    public function eat($food)
    {
        echo "I&#39;m eating ".$food;
        $this->breath();
    }
}
//实例化“人”类
$people = new Human();
$people->eat(&#39;rice&#39;);
//输出结果:I&#39;m eating rice Breath use the air...
?>

3. Special practices of PHP object-oriented programming
Some magic methods specific to the PHP language:

<?php
class Object
{
    public function __construct()
    {
        echo "当类在被实例化的时候,自动执行该函数";
    }
    public function __toString()
    {
        return "当对象被当作字符串形式输出时,自动执行该函数";
    }
    public function __invoke($value)
    {
        echo "当对象被当作函数调用时,自动执行该函数".$value;
    }
    /*
    *    当对象访问不存在的方法时,自动执行该函数。也称之为“方法重载”
    *    $fun : 方法名称
    *    $param : 传递的参数
    */
    public function __call($fun,$param)
    {
        echo "调用".$fun."方法不存在,传递的参数".implode(&#39;,&#39;,$param);
    }
    /*
    *    当对象访问不存在的静态方法时,自动执行该函数。
    *    $fun : 方法名称
    *    $param : 传递的参数
    */
    static function __callStatic($fun,$param)
    {
        echo "调用".$fun."静态方法不存在,传递的参数".implode(&#39;,&#39;,$param);
    }
    public function __get($key)
    {
        echo "当读取对象中不可访问(未定义)的属性值时,自动调用该函数。".$key."属性不可访问或未定义";
    }
    public function __set($key,$value)
    {
         echo "当给对象中不可访问(未定义)的属性赋值时,自动调用该函数。".$key."属性不可访问或未定义,值".$value;
    }
    public function __isset($key)
    {
        echo "判断对象中的属性不存在时,自动执行该函数。属性:".$key."值未定义";
    }
    public function __unset($key)
    {
        echo "释放对象中的不存在的属性值时,自动执行该函数。属性:".$key."值未定义";
    }
    public function __clone()
    {
        echo "当对象被克隆时,自动执行该函数。";
    }
    public function __destruct()
    {
        echo "当对象执行完成后,自动执行该函数";
    }
}
$obj = new Object();    //实例化对象时,调用__construct()方法
echo $obj;              //将对象以字符串形式输出时,调用__toString()方法
$obj(123);              //当对象以函数形式调用时,执行__invoke()方法
$obj->runTest();        //当调用对象中不存在的方法时,执行__call()方法
$obj::runTest();        //当调用对象中不存在的静态方法时,执行__callStatic()方法
$obj->name;             //当调用对象中不存在的成员属性时,执行__get()方法
$obj->name = "张三";    //当给对象中不存在的成员属性赋值时,执行__set()方法
isset($obj->name) ? 1 : 0;     //判断对象中不存在的成员属性时,执行__isset()方法
unset($obj->name);      //释放对象中的不存在的属性值时,执行__unset()方法
$obj2 = clone $obj;     //当对象被克隆时,执行__clone()方法
                        //对象执行完毕,执行__destruct()方法
?>

Related Recommended:

PHP object-oriented notes——123 Illustrated static properties and static methods

Study on the three major characteristics of PHP object-oriented

Detailed example of implementation of PHP object-oriented guestbook function


The above is the detailed content of A brief discussion on object-oriented programming in PHP. 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