php继承中方法重载(覆盖)的应用场合,php重载
本文实例分析了php继承中方法重载(覆盖)的应用场合。分享给大家供大家参考。具体分析如下:
方法重载(override)/覆盖——在什么情况下使用:当父类知道所有的子类都需要用到一个方法,但父类不知道怎么去写这个方法时,就需要用到方法的重载。这时候,可以让子类去重写,来覆盖这个方法。
通俗实例——父类(动物)知道其子类(猫和狗)都会叫,但它们的叫法都不一样,所以父类没法去写这个方法,只能让子类(猫和狗)去定义。代码如下:
<?php class Animal{ public $name; protected $price; function cry(){ echo "不知道动物怎么叫"; } } class Dog extends Animal{ function cry(){ echo "汪汪..."; } } class Pig extends Animal{ function cry(){ echo "哼哼..." } } ?>
方法重载/覆盖的要点与细节(读起来有点呦口):
1、要求子类的方法,其方法名称、参数列表与父类方法一模一样。如例子中cry(),不能添加参数,改成cry($naaa)等。注意:这里并不要求参数名一样,只是要求参数的个数是一样的。
2、所谓的重载或覆盖,并不是将父类的方法覆盖。也可以这么理解:如果子类有调用该方法时,如果在自己类里找不到这个方法,那么它会去找父类里,看有没有这个方法。这也是多态的理解
3、如果子类里某个方法,要把父类里相同名称方法里的内容继承下来,可以使用 parent::方法名 或 父类名::方法名 继承。在子类定义的方法内使用。
4、访问权限问题,子类的访问范围>=父类的访问范围,即如果父类是protected function cry(),子类则只能是protected或public。
希望本文所述对大家的php程序设计有所帮助。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

SublimeText3 Linux new version
SublimeText3 Linux latest version

Dreamweaver CS6
Visual web development tools

Dreamweaver Mac version
Visual web development tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft
