(2) PHP object-oriented theory 2
一. 魔术方法:
1. 魔术方法以“__”开头,是PHP的语法糖。语法糖是更实用的编码方式或技巧,使代码更易读。
2. __set与__get
<?php class Account{ private $user = 1 ; private $pwd = 2; public function __set($name,$value){ echo "Setting $name to $value \r\n"; $this ->$name = $value; } public function __get($name){ if (!isset($this->$name)){ echo 'no set '; $this->$name = 'set default value:'; } return $this->$name; } } $a = new Account(); echo $a -> user; echo "<br /><br />"; $a->user = 5; echo $a->$name; echo "<br /><br />"; echo $a->big;
2.__call和__callStatic:
(以下代码,未能执行成功)
<?php /* * 本代码没有执行成功 */ abstract class ActiveRecord{ protected static $table; protected $fieldValues; public $select; static function findById($id){ $query = "select * from " .static::$table ." where id = $id"; echo $query; return self::createDomain($query); } function __get($fieldname){ return $this->fieldvalues[$fieldname]; } static function __callStatic($method,$args){ $field = preg_replace('/^findBy(\w*)$','${1}',$method); $query = "select * from " .static::$table ." where $field='$args[0]"; return self::createDomain($query); } private static function createDomain($query){ echo "test"; $klass = get_called_class(); $domain = new $klass(); $domain->fieldvalues = array(); $domain->select = $query; foreach($klass::$fields as $field => $type){ $domain->fieldvalues[$field] = 'TODO:set from sql result'; } return $domain; } } class Customer extends ActiveRecord{ protected static $table = 'custdb'; protected static $fields = array( 'id' => 'int', 'email' => 'varchar', 'lastname' => 'varchar' ); public function __construct(){ echo "***"; } } class Sales extends ActiveRecord{ protected static $table = 'salesdb'; protected static $fields = array( 'id' => 'int', 'item' => 'varchar', 'qty' => 'int' ); } assert("select * from custdb where id = 123" == Customer::findById(123) ->select); assert("TODO: set from sql result" == Customer::findById(123)->email); assert("select * from salesdb where id = 321"== Sales::findById(321)->select); assert("select * from custdb where lastname = 'Denoncourt'"== Customer::findByLastname('Denoncourt')->select);
3.__toString
<?php header("Content-type: text/html; charset=utf-8"); class Account{ public $user = 1 ; private $pwd = 2 ; public function __toString(){ return "当前对象的用户是{$this->user},密码是{$this->pwd}"; } } $a = new Account(); echo $a; echo "<br /><br />"; echo PHP_EOL."==="; echo "<br /><br /><br />"; print_r($a);
二.继承与多态:
1. 继承:类与类之间有一种父与子的关系,子类继承父类的属性和方法,称为继承。
在继承里,子类拥有父类的方法和属性,同时子类也可以有自己的方法和属性。
<?php header("Content-type: text/html; charset=utf-8"); class person{ public $name = 'Tom'; public $gender; static $money = 10000; public function __construct(){ echo "这里是父类",PHP_EOL; } public function say(){ echo $this->name,"\tis",$this->gender,"\r\n"; } } class family extends person{ public $name; public $gender; public $age; static $money = 100000; public function __construct(){ parent::__construct(); echo "这里是子类",PHP_EOL; } public function say(){ echo "<br />我说".$this->name,"\tis\t",$this->gender,",and is \t", $this->age,PHP_EOL."<br />"; } public function cry(){ echo parent::$money,PHP_EOL; echo "%>-<%",PHP_EOL; echo self::$money,PHP_EOL; echo "(*^_^*)"; } public function read(){ echo "<br /><br /><br />read again".parent::say()."<br />"; } } $poor = new family(); $poor->name = 'Lee'; $poor->gender = 'female'; $poor->age = 25; $poor->say(); $poor->cry(); $poor->read(); /* * 疑问: * 我在子类上加了个方法叫read * 结果执行结果成了: * 这里是父类 这里是子类 我说Lee is female,and is 25 10000 %>-<% 100000 (*^_^*)Lee isfemale read again 为什么read again在lee is female后面……(我感觉应该先执行read again) */
在继承中,以parent指代父类,以self指代自身。以”::”(范围解析操作符)调用父类的方法。”::”操作符还用来作为类常量和静态方法的调用。
如果声明类成员或方法为static,就可以不实例化类而直接访问。
不能通过一个对象访问其中的静态成员(静态方法除外),也不能用“::”访问一个非静态方法。
继承是一种“是、像”的关系,而组合一种“需要”的关系。
从方法复用的角度考虑,如果两个类具有很多相同的代码和方法,可以从这两个类中抽象出一个父类,提供公共方法,然后两个类作为子类。提供个性方法。
继承的问题:
a. 继承破坏封装性。
b. 继承是紧耦合的。
c. 继承扩展复杂。
d. 不恰当地使用继承可能违反现实世界中的逻辑。
<?php class car{ public function addoil(){ echo "Add oil\r\n"; } } class bmw extends car{ } class benz{ public $car; public function __construct(){ $this->car = new car; } public function addoil(){ $this->car->addoil(); } } $bmw = new bmw(); $bmw ->addoil(); $benz = new benz(); $benz->addoil();
a. 继承树的抽象层一般不要多于三层。
b. 对于不是专门用于被继承的类使用final修饰符,可以防止重要方法被覆写。
c. 优先考虑组合关系可以提高代码的可重用性。
d. 子类是一种特殊的类型,不只是父类的一个角色。
e. 底层代码多用组合以提高效率,顶层(业务层)代码多用继承以提高灵活性。
2. 多态:
实际开发中,只要关心一个接口或基类的编程,而不必关心一个对象所属于的具体类。
<?php header("Content-type: text/html; charset=utf-8"); class employee{ protected function working(){ echo "本方法需要重载才能运行"; } } class teacher extends employee{ public function working(){ echo "教书"; } } class coder extends employee{ public function working(){ echo "敲代码"; } } class readBooks extends employee{ public function working(){ echo "我不看书的!"; } } function doprint($obj){ if(get_class($obj) == 'employee'){ echo "error"; }else{ $obj->working(); } } doprint(new teacher()); doprint(new coder()); doprint(new employee()); doprint(new readBooks());
总结:
a. 多态指同一类对象在运行时的具体化
b. PHP语言是弱类型的,实现多态更简单、更灵活
c. 类型转换不是多态
d. PHP中父类和子类被看作是‘继父’和‘继子’的关系,存在继承关系。子类无法向上转型为父类。
e. 多态的本质就是if...else,但实现的层级不同。
版权声明:本文为博主原创文章,未经博主允许不得转载。
以上就介绍了(二)PHP面向对象理论2,包括了方面的内容,希望对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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



The message "Your organization has asked you to change your PIN" will appear on the login screen. This happens when the PIN expiration limit is reached on a computer using organization-based account settings, where they have control over personal devices. However, if you set up Windows using a personal account, the error message should ideally not appear. Although this is not always the case. Most users who encounter errors report using their personal accounts. Why does my organization ask me to change my PIN on Windows 11? It's possible that your account is associated with an organization, and your primary approach should be to verify this. Contacting your domain administrator can help! Additionally, misconfigured local policy settings or incorrect registry keys can cause errors. Right now

Windows 11 brings fresh and elegant design to the forefront; the modern interface allows you to personalize and change the finest details, such as window borders. In this guide, we'll discuss step-by-step instructions to help you create an environment that reflects your style in the Windows operating system. How to change window border settings? Press + to open the Settings app. WindowsI go to Personalization and click Color Settings. Color Change Window Borders Settings Window 11" Width="643" Height="500" > Find the Show accent color on title bar and window borders option, and toggle the switch next to it. To display accent colors on the Start menu and taskbar To display the theme color on the Start menu and taskbar, turn on Show theme on the Start menu and taskbar

By default, the title bar color on Windows 11 depends on the dark/light theme you choose. However, you can change it to any color you want. In this guide, we'll discuss step-by-step instructions for three ways to change it and personalize your desktop experience to make it visually appealing. Is it possible to change the title bar color of active and inactive windows? Yes, you can change the title bar color of active windows using the Settings app, or you can change the title bar color of inactive windows using Registry Editor. To learn these steps, go to the next section. How to change title bar color in Windows 11? 1. Using the Settings app press + to open the settings window. WindowsI go to "Personalization" and then

Do you see "A problem occurred" along with the "OOBELANGUAGE" statement on the Windows Installer page? The installation of Windows sometimes stops due to such errors. OOBE means out-of-the-box experience. As the error message indicates, this is an issue related to OOBE language selection. There is nothing to worry about, you can solve this problem with nifty registry editing from the OOBE screen itself. Quick Fix – 1. Click the “Retry” button at the bottom of the OOBE app. This will continue the process without further hiccups. 2. Use the power button to force shut down the system. After the system restarts, OOBE should continue. 3. Disconnect the system from the Internet. Complete all aspects of OOBE in offline mode

Taskbar thumbnails can be fun, but they can also be distracting or annoying. Considering how often you hover over this area, you may have inadvertently closed important windows a few times. Another disadvantage is that it uses more system resources, so if you've been looking for a way to be more resource efficient, we'll show you how to disable it. However, if your hardware specs can handle it and you like the preview, you can enable it. How to enable taskbar thumbnail preview in Windows 11? 1. Using the Settings app tap the key and click Settings. Windows click System and select About. Click Advanced system settings. Navigate to the Advanced tab and select Settings under Performance. Select "Visual Effects"

We all have different preferences when it comes to display scaling on Windows 11. Some people like big icons, some like small icons. However, we all agree that having the right scaling is important. Poor font scaling or over-scaling of images can be a real productivity killer when working, so you need to know how to customize it to get the most out of your system's capabilities. Advantages of Custom Zoom: This is a useful feature for people who have difficulty reading text on the screen. It helps you see more on the screen at one time. You can create custom extension profiles that apply only to certain monitors and applications. Can help improve the performance of low-end hardware. It gives you more control over what's on your screen. How to use Windows 11

Many users will choose the Huawei brand when choosing smart watches. Among them, Huawei GT3pro and GT4 are very popular choices. Many users are curious about the difference between Huawei GT3pro and GT4. Let’s introduce the two to you. . What are the differences between Huawei GT3pro and GT4? 1. Appearance GT4: 46mm and 41mm, the material is glass mirror + stainless steel body + high-resolution fiber back shell. GT3pro: 46.6mm and 42.9mm, the material is sapphire glass + titanium body/ceramic body + ceramic back shell 2. Healthy GT4: Using the latest Huawei Truseen5.5+ algorithm, the results will be more accurate. GT3pro: Added ECG electrocardiogram and blood vessel and safety

Screen brightness is an integral part of using modern computing devices, especially when you look at the screen for long periods of time. It helps you reduce eye strain, improve legibility, and view content easily and efficiently. However, depending on your settings, it can sometimes be difficult to manage brightness, especially on Windows 11 with the new UI changes. If you're having trouble adjusting brightness, here are all the ways to manage brightness on Windows 11. How to Change Brightness on Windows 11 [10 Ways Explained] Single monitor users can use the following methods to adjust brightness on Windows 11. This includes desktop systems using a single monitor as well as laptops. let's start. Method 1: Use the Action Center The Action Center is accessible
