Home php教程 php手册 第九节--绑定 -- Classes and Objects in PHP5 [9]

第九节--绑定 -- Classes and Objects in PHP5 [9]

Jun 13, 2016 am 10:21 AM
and php5 Which Way binding access limit

第九节--绑定

除了限制访问,访问方式也决定哪个方法将被子类调用或哪个属性将被子类访问. 函数调用与函数本身的关联,以及成员访问与变量内存地址间的关系,称为绑定.

在计算机语言中有两种主要的绑定方式—静态绑定和动态绑定. 静态绑定发生于数据结构和数据结构间,程序执行之前. 静态绑定发生于编译期, 因此不能利用任何运行期的信息. 它针对函数调用与函数的主体,或变量与内存中的区块. 因为PHP是一种动态语言,它不使用静态绑定. 但是可以模拟静态绑定.

动态绑定则针对运行期产生的访问请求,只用到运行期的可用信息. 在面向对象的代码中,动态绑定意味着决定哪个方法被调用或哪个属性被访问,将基于这个类本身而不基于访问范围.

Public和protected成员的动作类似于PHP的前几个版本中函数的动作,使用动态绑定. 这意味着如果一个方法访问一个在子类中被覆写的类成员,并是一个子类的实例,子类的成员将被访问(而不是访问父类中的成员).

看例子6.10. 这段代码输出” Hey! I am Son.” 因为当PHP调用getSalutation, 是一个Son的实例,是将Father中的salutation覆写而来. 如果salutation是public的,PHP将产生相同的结果. 覆写方法的操作很类似.在Son中,对于identify的调用绑定到那个方法.

即使在子类中访问方式被从protected削弱成public, 动态绑定仍然会发生. 按照访问方式使用的原则,增强对于类成员的访问限制是不可能的. 所以把访问方式从public改变成protected不可能进行.

Listing 6.10 Dynamic binding 动态绑定

<?php 

   class Father 

   { 

       protected $salutation = "Hello there!"; //问候 



       public function getSalutation() 

       { 

           print("$this->salutation
"); 

           $this->identify(); 

       } 



       protected function identify() 

       { 

           print("I am Father.<br>
"); 

       } 

   }; 



   class Son extends Father 

   { 

       protected $salutation = "Hey!";  //父类中的protected $salutation 被覆写 



       protected function identify()    //父类中的protected identify() 被覆写 

       { 

           print("I am Son.<br>
"); 

       } 

   }; 



   $obj = new Son(); 

   $obj->getSalutation();  //输出Hey! I am Son. 

?> 
Copy after login



//注: 在子类中没有覆写getSalutation(),但实际上仍然存在一个getSalutation().这个类中的$salutation和identify()
//与Son子类的实例中的getSalutation()方法动态绑定,所以调用Son的实例的getSalutation()方法,
//将调用Son类中的成员salutation及identify(),而不是父类中的成员salutation及identify().

Private成员只存在于它们所在的类内部. 不像public和protected成员那样,PHP模拟静态绑定. 看例子6.11. 它输出”Hello there! I am Father.”,尽管子类覆写了salutation的值. 脚本将this->salutation和当前类Father绑定. 类似的原则应用于private方法identify().

Listing 6.11 Binding and private members
<?php 

   class Father 

   { 

       private $salutation = "Hello there!"; 



       public function getSalutation() 

       { 

           print("$this->salutation
"); 

           $this->identify(); 

       } 



       private function identify() 

       { 

           print("I am Father.<br>
"); 

       } 

   } 



   class Son extends Father 

   { 

       private $salutation = "Hey!"; 

       private function identify() 

       { 

           print("I am Son.<br>
"); 

       } 

   } 



   $obj = new Son(); 

   $obj->getSalutation(); //输出Hello there! I am Father. 

?>
Copy after login



动态绑定的好处是允许继承类来改变父类的行为,同时可以保持父类的接口和功能. 看例子6.12. 由于使用了动态绑定,在deleteUser中被调用的isAuthorized的version 可以由对象的类型来确定. 如果是一个普通的user,PHP调用User::isAuthorized会返回FALSE.如果是一个AuthorizedUser的实例,PHP调用AuthorizedUser::isAuthorized,将允许deleteUser顺利执行.

//haohappy注:用一句话说清楚,就是对象类型与方法,属性绑定. 调用一个父类与子类中都存在的方法或访问一个属性时,会先判断实例属于哪种对象类型,再调用相应的类中的方法和属性.

Listing 6.12 动态绑定的好处
<?php 

   class User //用户 

   { 

       protected function isAuthorized()  //是否是验证用户 

       { 

           return(FALSE); 

       } 



       public function getName()  //获得名字 

       { 

           return($this->name); 

       } 



       public function deleteUser($username) //删除用户 

       { 

           if(!$this->isAuthorized()) 

           { 

               print("You are not authorized.<br>
"); 

               return(FALSE); 

           } 



           //delete the user 

           print("User deleted.<br>
"); 

       } 

   } 



   class AuthorizedUser extends User //认证用户 

   { 

       protected function isAuthorized() //覆写isAuthorized() 

       { 

           return(TRUE); 

       } 

   } 



   $user = new User; 

   $admin = new AuthorizedUser; 



   //not authorized 

   $user->deleteUser("Zeev"); 



   //authorized 

   $admin->deleteUser("Zeev"); 

?> 
Copy after login



为什么private的类成员模拟静态绑定? 为了回答这个问题, 你需要回忆一下为什么需要有private成员.什么时候用它们来代替protected成员是有意义的?

private成员只有当你不想让子类继承改变或特殊化父类的行为时才用到. 这种情况比你想像的要少. 通常来说,一个好的对象分层结构应当允许绝大多数功能被子类特殊化,改进,或改变—这是面向对象编程的基础之一. 一定的情况下需要private方法或变量,例如当你确信你不想允许子类改变父类中的某个特定的部份.

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Two Point Museum: All Exhibits And Where To Find Them
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

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)

Can two WeChat accounts be bound to the same bank card? Can two WeChat accounts be bound to the same bank card? Aug 25, 2023 pm 03:13 PM

Two WeChat accounts cannot be bound to the same bank card. Bind a bank card to a WeChat account: 1. Open the WeChat application, click the "Me" option, and then select the "Pay" option; 2. Select the "Add Bank Card" option and enter the bank card information as prompted; 3. Once the bank card is successfully bound, users can use the bank card to make payments and transfers in WeChat.

What is the difference between php5 and php8 What is the difference between php5 and php8 Sep 25, 2023 pm 01:34 PM

The differences between php5 and php8 are in terms of performance, language structure, type system, error handling, asynchronous programming, standard library functions and security. Detailed introduction: 1. Performance improvement. Compared with PHP5, PHP8 has a huge improvement in performance. PHP8 introduces a JIT compiler, which can compile and optimize some high-frequency execution codes, thereby improving the running speed; 2. Improved language structure, PHP8 introduces some new language structures and functions. PHP8 supports named parameters, allowing developers to pass parameter names instead of parameter order, etc.

How to implement editable tables in Vue How to implement editable tables in Vue Nov 08, 2023 pm 12:51 PM

Tables are an essential component in many web applications. Tables usually have large amounts of data, so tables require some specific features to improve user experience. One of the important features is editability. In this article, we will explore how to implement editable tables using Vue.js and provide specific code examples. Step 1: Prepare the data First, we need to prepare the data for the table. We can use a JSON object to store the table's data and store it in the data property of the Vue instance. In this case

How to access JSONNode's JSON fields, arrays and nested objects in Java? How to access JSONNode's JSON fields, arrays and nested objects in Java? Aug 30, 2023 pm 11:05 PM

A JsonNode is Jackson's JSON tree model that can read JSON into JsonNode instances and write JsonNode into JSON. We can use Jackson to read JSON into a JsonNode by creating an ObjectMapper instance and calling the readValue() method. We can access fields, arrays or nested objects using the get() method of the JsonNode class. We can use the asText() method to return a valid string representation and convert the node's value to Javaint using the asInt() method of the JsonNode class. In the example below we can access Json

iOS 17: How to control which apps can access your photos iOS 17: How to control which apps can access your photos Sep 13, 2023 pm 09:09 PM

In iOS17, Apple has more control over what apps can see in photos. Read on to learn how to manage app access by app. In iOS, Apple's in-app photo picker lets you share specific photos with the app, while the rest of your photo library remains private. Apps must request access to your entire photo library, and you can choose to grant the following access to apps: Restricted Access – Apps can only see images that you can select, which you can do at any time in the app or by going to Settings &gt ;Privacy & Security&gt;Photos to view selected images. Full access – App can view photos

How to remove comment restrictions on video accounts? What is the word limit for comments on a video account? How to remove comment restrictions on video accounts? What is the word limit for comments on a video account? Mar 22, 2024 pm 02:11 PM

With the popularity of video accounts on social media, more and more people are beginning to use video accounts to share their daily lives, insights and stories. However, some users may experience comments being restricted, which can leave them confused and dissatisfied. 1. How to remove comment restrictions on video accounts? To lift the restriction on commenting on a video account, you must first ensure that the account has been properly registered and real-name authentication has been completed. Video accounts have requirements for comments. Only accounts that have completed real-name authentication can lift comment restrictions. If there are any abnormalities in the account, these issues need to be resolved before comment restrictions can be lifted. 2. Comply with the community standards of the video account. Video accounts have certain standards for comment content. If the comment involves illegal content, you will be restricted from speaking. To lift comment restrictions, you need to abide by the community of the video account

BTCC tutorial: How to bind and use MetaMask wallet on BTCC exchange? BTCC tutorial: How to bind and use MetaMask wallet on BTCC exchange? Apr 26, 2024 am 09:40 AM

MetaMask (also called Little Fox Wallet in Chinese) is a free and well-received encryption wallet software. Currently, BTCC supports binding to the MetaMask wallet. After binding, you can use the MetaMask wallet to quickly log in, store value, buy coins, etc., and you can also get 20 USDT trial bonus for the first time binding. In the BTCCMetaMask wallet tutorial, we will introduce in detail how to register and use MetaMask, and how to bind and use the Little Fox wallet in BTCC. What is MetaMask wallet? With over 30 million users, MetaMask Little Fox Wallet is one of the most popular cryptocurrency wallets today. It is free to use and can be installed on the network as an extension

How to bind a sub-account on Xiaohongshu? How does it check whether the account is normal? How to bind a sub-account on Xiaohongshu? How does it check whether the account is normal? Mar 21, 2024 pm 10:11 PM

In today's era of information explosion, the construction of personal brand and corporate image has become increasingly important. As the leading fashion life sharing platform in China, Xiaohongshu has attracted a large number of user attention and participation. For those users who want to expand their influence and improve the efficiency of content dissemination, binding sub-accounts has become an effective means. So, how does Xiaohongshu bind a sub-account? How to check whether the account is normal? This article will answer these questions for you in detail. 1. How to bind a sub-account on Xiaohongshu? 1. Log in to your main account: First, you need to log in to your Xiaohongshu main account. 2. Open the settings menu: click &quot;Me&quot; in the upper right corner, and then select &quot;Settings&quot;. 3. Enter account management: In the settings menu, find the &quot;Account Management&quot; or &quot;Account Assistant&quot; option and click

See all articles