search
HomeBackend DevelopmentPHP TutorialAnalyze the three major characteristics of PHP object-oriented

Analyze the three major characteristics of PHP object-oriented

Jun 26, 2017 pm 03:20 PM
phpobjectfeatureparseFor

class BenHang extends Card{     /*构造函数与及构造的继承*/ function __construct($cardno,$pwd, $name,$money){
         parent::__construct($cardno,$pwd, $name,$money);
     }    
     function take($money){         echo "本行取款{$money}没有手续费·····<br>";
     }function zhuan($money){         echo "本行转账{$money}·····<br>";
     }
    
 }$benhang=new BenHang(123,344,444,444);$benhang->check();$benhang->take(234);$benhang->zhuan(4555);/*其他银行卡的类*/class Qita extends Card{function __construct($cardno,$pwd, $name,$money){
         parent::__construct($cardno,$pwd, $name,$money);
     }    function take($money){         echo "非本行取款{$money}有手续费2元·····<br>";
     }
}$qita=new Qita(123,344,444,444);$qita->check();$qita->take(99);

PHP's three major characteristics: inheritance, packaging, polymorphism

1. How to implement inheritance?

Use the extends keyword for the subclass to inherit the parent class;

class Student extends Person{}# 2. Things to note when implementing inheritance?

① Subclasses can only inherit non-private properties of the parent class.

②After a subclass inherits a parent class, it is equivalent to copying the properties and methods of the parent class to the subclass, which can be called directly using $this.

③ PHP can only support single inheritance and does not support one class inheriting multiple classes. But a class carries out multi-level inheritance;

class Student extends Chengnian{}

//Student class has both Chengnian class and Person class Properties and methods

3. Method override (method rewriting)## Condition ① Subclass Inherit from parent class.

Condition ② The subclass overrides the existing method of the parent class.

Meeting the above two conditions is called method coverage. After overriding, when a subclass calls a method, the subclass's own method will be called. Similarly, in addition to method overrides, subclasses can also have attributes with the same name as the parent class for attribute overrides.

4. If the subclass overrides the parent class method, how to call the parent class method with the same name in the subclass?

partent::method name();

Therefore, when a subclass inherits a parent class, it needs to be The first step in the construction is to call the parent class constructor to copy.

       function __construct($name,$sex,$school){

             parent::__construct($name,$sex);

             $this->school = $school;

       }

实例一枚:

class Person{protected $name;public $sex;
        function __construct($name,$sex){     //声明构造函数            $this->name = $name;
            $this->sex = $sex;
        }
        function say(){
            echo "我叫{$this->name},我是{$this->sex}生!<br>";
        }
    }    class Student extends Person{                       //子类继承父类public $school;                                           function __construct($name,$sex,$school){          //子类的构造函数            parent::__construct($name,$sex);        //调用父类构造进行复制$this->school = $school;
        }
        
        function program(){
            echo "PHP真好玩!我爱PHP!PHP是世界上最好用的编程语言!<br>";
        }
        
        function say(){
            parent::say();                      //重写父类的同名方法echo "我是{$this->school}的";
        }
    }
    
    $zhangsan = new Student("张三","男","起航");
    $zhangsan->say();
    $zhangsan->program();

 

二、封装

  1、什么是封装?
   通过访问修饰符,将类中不需要外部访问的属性和方法进行私有化处理,以实现访问控制。
【注意】是实现访问控制,而不是拒绝访问。 也就是说,我们私有化属性之后,需要提供对应的方法,让用户通过我们提供的方法处理属性。
2、封装的作用?
    ①使用者只关心类能够提供的功能,而不必关心功能实现的细节!(封装方法)
    ②对用户的数据进行控制,防止设置不合法数据,控制返回给用户的数据(属性封装+set/get方法)
  3、实现封装操作?
   ① 方法的封装
    对于一些只在类内部使用的方法,而不像对外部提供使用。那么,这样的方法我们可以使用private进行私有化处理。
     private function formatName(){}        //这个方法仅仅能在类内部使用$this调用
         function showName(){
          $this -> formatName();
       }
②属性的封装+set/get方法
In order to control the setting and reading of attributes, you can privatize the attributes and require users to set them through the set/get methods we provide
        Private $ Age;
# FUNCTION SETAGE ($ Age) {
# 000
}
# FUNCTION GETAGE () {
## Return $ This- & GT
## }
##         $Object-> getAge();
                            $Object-> setAge(12);
③ Attribute encapsulation + magic method
##private $age;
## Function __get($key){
Return $this->$key;
}
## Function __Set ($ key, $ value) {
# $ this- & gt; $ key = $ value;
## Call the __get() magic method, and pass the accessed attribute name to the __get() method; ##//When setting the object's private attributes, the __set() magic method is automatically called, and the set attribute name and attribute value are passed to the __set() method;
【 注意】在魔术方法中,可以使用分支结构,判断$key的不同,进行不同操作。
  4、关于封装的魔术方法:
     ① __set($key,$value):给类私有属性赋值时自动调用,调用时给方法传递两个参数:需要设置的属性名、属性值;
     ② __get($key):读取类私有属性时自动调用,调用时给方法传递一个参数:需要读取的属性名;
     ③ __isset($key):外部使用isset()函数检测私有属性时,自动调用。
       >>> 类外部使用isset();检测私有属性,默认是检测不到的。false
       >>> 所以,我们可以使用__isset();函数,在自动调用时,返回内部检测结果。
       function __isset($key){
              return isset($this->$key);
            }
当外部使用isset($对象名->私有属性);检测时,将自动调用上述__isset()返回的结果!
    ④ __unset($key):外部使用unset()函数删除私有属性时,自动调用;
       function __unset($key){
           unset($this->$key);
           }
  当外部使用unset($对象名->私有属性);删除属性时,自动将属性名传给__unset(),并交由这个魔术方法处理。
实例一枚
class Person{public $name;public $age;public $sex;
        function __construct($name, $age,$sex){
            $this->name=$name;
            $this->setAge($age);
            $this->setSex($sex);
        }
        function setAge($age){if($age>=0&&$ageage=$age;
            }else{
                die("年龄输入有误!!!");
            }
        }
        function setSex($sex){if($sex=="女"||$sex=="男"){return    $this->sex=$sex;
            }else{
                die("性别输入有误!!!");
            }
        }
        function say(){
            echo "我的名字叫{$this->name},我的年龄{$this->age},我的性别是{$this->sex}<br>";
        }
    }class Work extends Person{private $position;
        function __construct($name, $age,$sex,$position){
            parent::__construct($name, $age,$sex);
            $this->job=$job;
            $this->setPosition($position);
        }
        function setPosition($position){
            $arr=['总监','董事长','程序员','清洁工'];if(in_array($position, $arr)){return $this->position=$position;
            }else{
                die("不存在该职位");
            }
        }        
        function __set($key,$value){if($key=="age"){return    parent::setAge($value);
            }
            elseif($key=="sex"){return    parent::setSex($value);
            }
            elseif($key=="position"){return $this->setPosition($value);
            }return $this->$key=$value;
        }
        
        function say(){
            parent::say();
            echo "我的职位是{$this->position}";
        }
     }
     
    $zhangsan=new Work("张三",22,"男","总监");
    $zhangsan->setSex("女");
    $zhangsan->setAge(30);//  $zhangsan->setPosition("董事长");$zhangsan->position="董事长";
    $zhangsan->name="lisi";$zhangsan->say();

 

三.多态
  3.1、什么是多态?
     多态实现多态的前提是实现继承。
      1.一个类被多个子类继承,如果这个类的某个方法在多个子类中表现出不同的功能,我们称这种行为为多态。在PHP中的方法重写,
     2.实现多态的必要途径:
      ⑴子类继承父类;
      ⑵重写父类方法;
      ⑶父类引用指向子类对象;
     
/*墨盒接口
 * 纸张接口*/
 interface InkBox{     function color();
 }interface Paper{     function sizes();
 }class Computer{function fangfa(InkBox $a,Paper $b){     //父类引用echo "即将开始打印····<br>";    $a->color();$b->sizes();echo "打印结束···<br>";    
    
  }
}class Color implements InkBox{function color(){echo "正在装载彩色墨盒<br>";echo "实现彩色墨盒<br>";
    }
}class White implements InkBox{function color(){echo "正在装载黑白墨盒<br>";    echo "实现黑白墨盒<br>";
    }
}class A4 implements Paper{function sizes(){echo "正在加载A4纸张<br>";echo "实现A4纸张<br>";
    }
}class A5 implements Paper{function sizes(){echo "实现A5纸张<br>";
    }
}$com=new Computer();//创建对象$com->fangfa(new Color(),new A4());//子类对象

 

 

The above is the detailed content of Analyze the three major characteristics of PHP object-oriented. 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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.