Home Backend Development PHP Tutorial Detailed explanation of overloading parent class in subclass in object-oriented PHP_PHP tutorial

Detailed explanation of overloading parent class in subclass in object-oriented PHP_PHP tutorial

Jul 13, 2016 am 10:49 AM
php one time about object tidy article Detailed explanation Overload For

This article will give you a detailed explanation of overloading parent classes in PHP object-oriented subclasses. I hope this article will help you understand overloading parent classes in PHP subclasses.


Because functions with the same name cannot exist in PHP, methods with the same name cannot be defined in the same class. The overloading mentioned here means that a method with the same name as the parent class can be defined in a subclass to override the method inherited from the parent class.


Overloading parent class methods in subclasses

The code is as follows Copy code


class Person{
                                                                                                                   public $name;                                                                                                                                                               public function __construct($name="" ){
$this->name =$name;
                                                                                                                  }
             public function say(){
echo "My name is".$this->name ;
           }
                                                                                                      }
?>
class Student extends Person{
                                                                                                               public $name;                                                                                                                                             public function __construct($name=""){
$this->name =$name;
                                                                                                          }
//Here defines a method with the same name as the parent class, overwriting and rewriting the speaking method in the parent class
             public function say(){
echo "My name is ".$this->name ." and I am 25 years old" ;
           }
                                                                                                      }
?>

Overriding methods and access permissions

An overridden method in a subclass cannot use more restrictive access permissions than the overridden method in the parent class.

If the access permission of the method in the parent class is protected, then the permissions of the method to be overridden in the subclass must be protected or public; If the method in the parent class is public, then the permissions of the method to be overridden in the subclass must be It can only be public. Perhaps this is why subclasses can inherit private members of the parent class, but cannot use them.

Number of parameters when rewriting

Subclasses can have a different number of parameters than the parent class. For example, in the following constructor, an additional parameter $age is added.

The code is as follows Copy code
 代码如下 复制代码

 

class Student extends Person{

public $name;
public $age;

public function __construct($name="",$age=25){
$this->name =$name; 

                $this->age =$age; 

          } 

          public  function say(){ 

                echo "我叫".$this->name .",今年".$this->age."岁了" ;   

           }  
                                                   

 } 
 ?>

<🎜> class Student extends Person{ <🎜> <🎜>                                                           <🎜> public $name; <🎜>            public $age;                                                                                                                                     <🎜> public function __construct($name="",$age=25){ <🎜> $this->name =$name; $this->age =$age;         }  public function say(){                         echo "My name is ".$this->name .", and this year ".$this->age." is old";                                                                                                                                                                                                                        } ?>

Constructor overriding

The "number of parameters during rewriting" mentioned above has already enabled the subclass to rewrite the constructor of the parent class, but this is not a good way of writing. If you observe carefully, you will find that, The above subclass Student's rewriting of the parent class's Person constructor is actually adding an extra parameter to the parent class's constructor function, but also copying the original parameters of the parent class, because the structure of the parent class Person The function only has one parameter, so we don’t have any trouble writing it down. However, if there is more than one parameter, but several or more, then you will find that it is cumbersome. So is there any way to simplify this problem? Woolen cloth? The answer is yes, you can use "parent::method name" to call the overridden method in the parent class in the overloaded method of the subclass. For example, use "parent::__construct()" to call the overridden constructor method in the parent class. Other methods are similar, so the above code can be simplified to:

The code is as follows Copy code
 代码如下 复制代码

 

class Student extends Person{

public $name;

public $age;

public function __construct($name="",$age=25){

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

$this->age =$age; 
         } 

           public  function say(){ 
             parent::say(); 

              echo ",今年".$this->age."岁了" ;   

          }  
                                         
 } 
 ?>

<🎜> class Student extends Person{ <🎜> <🎜>                                                            <🎜> public $name; <🎜> <🎜> public $age;
                                                                                                                     public function __construct($name="",$age=25){ <🎜> <🎜> parent::__construct($name,$age); <🎜> <🎜> $this->age =$age;
                                                                                              public function say(){
               parent::say(); echo ", this year".$this->age."year old" ;                                                                                                                                                                                                                 }
?>

Let’s look at another example

PHP5 rewriting method
First set up a parent class. This parent class is the "Dog" class. This class describes the characteristics of dog.

Dog has 2 eyes, can run and bark. Just describe it like this.

I have a dog, which is a puppy. It conforms to the characteristics of Dog, but it is different.

My puppy has a name. My puppy is too small. He can’t bark loudly, he can only hum.

We use the concept of inheritance to implement this design.

The code is as follows Copy code
 代码如下 复制代码

// 狗有两只眼睛,会汪汪叫,会跑.
class Dog {
protected $eyeNumber =2; //属性
//返回封装属性的方法.
public function getEyeNumber(){
return $this->eyeNumber;
 }
 //狗会叫 
 public function  yaff(){
  return  "Dog yaff, wang ..wang ..";
 }
 //狗会跑
 public function  run(){
  return  "Dog run..running ...";
 }
}
$dog = new Dog();
echo "dog have ".$dog->getEyeNumber()." eyes.
";
echo $dog->yaff() ."
".$dog->run();
echo  "

";
//这是我的小狗叫"狗狗",它很小.不会汪汪叫,只会哼哼哼..
class MyDog extends Dog {
 private $name = "狗狗";
 public function getName(){
  return $this->name;
 }
    public function  yaff(){
  return  $this->name." yaff, heng...heng ..";
 } 
}
$myDog = new MyDog();
echo $myDog->getName()." have ".$myDog->getEyeNumber()." eyes.
";
echo $myDog->yaff() ."
".$myDog->run();
?>

程序运行结果:

dog have 2 eyes.
Dog yaff, wang ..wang ..
Dog run..running ...

狗狗 have 2 eyes.
狗狗 yaff, heng...heng ..
Dog run..running ...

// The dog has two eyes, can bark, and can run.
class Dog {

protected $eyeNumber =2; //Attribute

//Return the method of encapsulating attributes.

public function getEyeNumber(){
代码如下 复制代码

// 简化dog类和mydog类,演示重写的访问权限.
class Dog {
protected $eyeNumber =2; //属性
//返回封装属性的方法.
public function getEyeNumber(){
return $this->eyeNumber;
 } 
}

class MyDog extends Dog {
 protected function getEyeNumber(){
  return $this->eyeNumber;
 } 
}
/*
class MyDog extends Dog {
 private function getEyeNumber(){
  return $this->eyeNumber;
 } 
}
*/

?>

程序运行结果:
 Fatal error: Access level to MyDog::getEyeNumber() must be public (as in class Dog) in E:PHPProjectstest.php on line 15

return $this->eyeNumber; } //Dogs can bark public function yaff(){ return "Dog yaff, wang ..wang .."; } //Dogs can run public function run(){ return "Dog run..running ..."; } } $dog = new Dog(); echo "dog have ".$dog->getEyeNumber()." eyes.
"; echo $dog->yaff() ."
".$dog->run(); echo "

"; //This is my puppy called "Dog". It is very small. It can't bark, it can only hum.. class MyDog extends Dog { private $name = "dog"; public function getName(){ Return $this->name; } Public function yaff(){ return $this->name." yaff, heng...heng .."; } } $myDog = new MyDog(); echo $myDog->getName()." have ".$myDog->getEyeNumber()." eyes.
"; echo $myDog->yaff() ."
".$myDog->run(); ?> Program execution result: dog has 2 eyes. Dog yaff, wang ..wang .. Dog run..running ... The dog has 2 eyes. Dog yaff, heng...heng .. Dog run..running ...
Overriding methods and access permissions An overridden method in a subclass cannot use more restrictive access permissions than the overridden method in the parent class. When the parent class is public and the subclass is private.
The code is as follows Copy code
// Simplify the dog class and mydog class to demonstrate rewritten access rights.<🎜> class Dog {<🎜> protected $eyeNumber =2; //Attribute<🎜> //Return the method of encapsulating attributes.<🎜> public function getEyeNumber(){ <🎜> Return $this->eyeNumber; } } class MyDog extends Dog { protected function getEyeNumber(){ Return $this->eyeNumber; } } /* class MyDog extends Dog { private function getEyeNumber(){ Return $this->eyeNumber; } } */ ?> Program execution result: Fatal error: Access level to MyDog::getEyeNumber() must be public (as in class Dog) in E:PHPProjectstest.php on line 15

When the parent class is public and the subclass is protected.

The code is as follows
 代码如下 复制代码

// 简化dog类和mydog类,演示重写的访问权限.
class Dog {
protected $eyeNumber =2; //属性
//返回封装属性的方法.
public function getEyeNumber(){
return $this->eyeNumber;
 } 
}

class MyDog extends Dog {
 private function getEyeNumber(){
  return $this->eyeNumber;
 } 
}

?>

程序运行结果:

 Fatal error: Access level to MyDog::getEyeNumber() must be public (as in class Dog) in E:PHPProjectstest.php on line 15

Copy code


代码如下 复制代码


// 简化dog类和mydog类,演示重写方法的参数.
class Dog {
protected $eyeNumber =2; //属性
//返回封装属性的方法.
public function getEyeNumber(){
return $this->eyeNumber;
 } 
}
class MyDog extends Dog {
 //重写的方法与父类的方法有不同的参数数量.
 public function getEyeNumber($eys){
  $this->eyeNumber = $eys;
  return $this->eyeNumber;
 } 
}

$myDog = new MyDog();
echo "my dog hava ".$myDog->getEyeNumber(3) ." eyes.";
//啸天犬..哈..
//下面这句会报一个丢失参数的错误.
//echo "my dog hava ".$myDog->getEyeNumber() ." eyes.";
?>

程序运行结果:

 my dog hava 3 eyes.

// Simplify the dog class and mydog class to demonstrate rewritten access rights.

class Dog {

protected $eyeNumber =2; //Attribute

//Return the method of encapsulating attributes.

public function getEyeNumber(){

return $this->eyeNumber;

}
 代码如下 复制代码

//2-2 / extends1.php
//构造函数继承的问题.
class Animal{
public $legNum = 0;
public function __construct(){
$this->legNum = 4;
  echo "I am an animal
";
 }
}
class Dog1 extends Animal {
 public function __construct(){
  $this->legNum = 4;
  echo "I am a Dog .
";
 }
}
$dog1 = new Dog1();
echo "
";
echo  "legNum is ".$dog1->legNum;
/*
实例化子类时.构造函数被调用了.
*/
?>

程序运行结果:

 I am a Dog . 
legNum is 4

}

class MyDog extends Dog { private function getEyeNumber(){ return $this->eyeNumber; } } ?> Program execution result: Fatal error: Access level to MyDog::getEyeNumber() must be public (as in class Dog) in E:PHPProjectstest.php on line 15 Number of parameters when rewriting Subclasses can have a different number of parameters than the parent class. (This is different from java, PHP is a weakly typed language.)
The code is as follows Copy code
// Simplify the dog class and mydog class and demonstrate the parameters of the overridden method.<🎜> class Dog {<🎜> protected $eyeNumber =2; //Attribute<🎜> //Return the method of encapsulating attributes.<🎜> public function getEyeNumber(){ <🎜> return $this->eyeNumber; } } class MyDog extends Dog { //The overridden method has a different number of parameters than the parent class method. public function getEyeNumber($eys){ $this->eyeNumber = $eys; return $this->eyeNumber; } } $myDog = new MyDog(); echo "my dog ​​hava ".$myDog->getEyeNumber(3) ." eyes."; //Howling Sky Dog...ha... //The following sentence will report a missing parameter error. //echo "my dog ​​hava ".$myDog->getEyeNumber() ." eyes."; ?> Program execution result: my dog ​​hava 3 eyes. Constructor overriding In the following example, both the parent class and the subclass have their own constructors. When the subclass is instantiated, the constructor of the subclass is called, but the constructor of the parent class is not called. Please compare the first Section constructor inheritance.
The code is as follows Copy code
//2-2 / extends1.php<🎜> //Problems with constructor inheritance.<🎜> class Animal{<🎜> public $legNum = 0; <🎜> public function __construct(){<🎜> $this->legNum = 4; echo "I am an animal
"; } } class Dog1 extends Animal { public function __construct(){ $this->legNum = 4; echo "I am a Dog .
"; } } $dog1 = new Dog1(); echo "
"; echo "legNum is ".$dog1->legNum; /* When instantiating a subclass, the constructor is called. */ ?> Program execution result: I am a Dog . legNum is 4 Note: This is different from Java. In Java, constructors cannot be inherited, and when a subclass is instantiated, the constructor of the subclass is called, and the constructor of the parent class is also called.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/632690.htmlTechArticleThis article will give you a detailed explanation of overloading parent classes in object-oriented subclasses in PHP. I hope this article It will be helpful for you to understand overloading parent classes in PHP subclasses. Because it cannot be saved in PHP...
Statement of this Website
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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1662
14
PHP Tutorial
1261
29
C# Tutorial
1234
24
How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

See all articles