Inheritance and method overloading of php classes

无忌哥哥
Release: 2023-04-01 20:58:02
Original
1441 people have browsed it

//Use the autoloader to load classes: (short version)

spl_autoload_register(function($className){
    require './class/'.$className.'.php'; 
});
Copy after login

//$smartPhone = new SmartPhone('Apple','iPhone8', 5888);

/ ///There are no these three attributes in the SmartPhone class at this time, can they be output?

//echo 'Brand: '.$smartPhone->brand.'
'; //Normal :public can be accessed externally

//echo 'Model: '.$smartPhone->model.'
'; //Error: protected can only be accessed in the current class and subclasses

//echo 'Price: '.$smartPhone->price. '
';//Error: private is only accessible to the current class

* What if these attributes can be accessed normally?

* There are two options to achieve

* 1. Set all access controls of related properties in the parent class MobilePhone to public

* 2. Set the parent class MobilePhone The access control of all relevant attributes in is set to protected, and a query is created in the subclass SmartPhone

* We adopt the second option

$smartPhone = new SmartPhone('HUAWEI','P20', 5488,true,true);
//下面我们换一组数据来初始化对象,验证parent::__contrunctor()
$smartPhone = new SmartPhone('MI','MIX2', 3599,true,true);
//此时SmartPhone类中并无这三个属性,可以输出吗?
echo &#39;品牌: &#39;.$smartPhone->brand.&#39;<br>&#39;; 
echo &#39;型号: &#39;.$smartPhone->model.&#39;<br>&#39;; 
echo &#39;价格: &#39;.$smartPhone->price. &#39;<br>&#39;;
//下面输出二个在子类中扩展的属性
echo &#39;照相:&#39;.($smartPhone->camera?&#39;支持&#39;:&#39;没有&#39;).&#39;<br>&#39;;
echo &#39;上网:&#39;.($smartPhone->internet?&#39;支持&#39;:&#39;没有&#39;).&#39;<br>&#39;;
echo $smartPhone->call().&#39;<br>&#39;; //call()是父类中的方法
echo $smartPhone->game().&#39;<br>&#39;; //game()是子类中的方法
Copy after login

The above is the detailed content of Inheritance and method overloading of php classes. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!