Home > Article > Backend Development > Inheritance and method overloading of php classes
//Use the autoloader to load classes: (short version)
spl_autoload_register(function($className){ require './class/'.$className.'.php'; });
//$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.'0c6dc11e160d3b678d68754cc175188a'; //Normal :public can be accessed externally
//echo 'Model: '.$smartPhone->model.'0c6dc11e160d3b678d68754cc175188a'; //Error: protected can only be accessed in the current class and subclasses
//echo 'Price: '.$smartPhone->price. '0c6dc11e160d3b678d68754cc175188a';//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 '品牌: '.$smartPhone->brand.'<br>'; echo '型号: '.$smartPhone->model.'<br>'; echo '价格: '.$smartPhone->price. '<br>'; //下面输出二个在子类中扩展的属性 echo '照相:'.($smartPhone->camera?'支持':'没有').'<br>'; echo '上网:'.($smartPhone->internet?'支持':'没有').'<br>'; echo $smartPhone->call().'<br>'; //call()是父类中的方法 echo $smartPhone->game().'<br>'; //game()是子类中的方法
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!