Home php教程 php手册 第八节--访问方式--ClassesandObjectsinPHP58

第八节--访问方式--ClassesandObjectsinPHP58

Jun 13, 2016 am 10:24 AM
Way access

/* +-------------------------------------------------------------------------------+ | = 本文为Haohappy读> | = 中Classes and Objects一章的笔记 | = 翻译为主+个人心得 | = 为避免可能发生的不必要的麻烦请勿转载,谢谢 | = 欢迎批评指正,希望和所有PHP爱好者共同进步! +-------------------------------------------------------------------------------+ */ 第八节--访问方式 PHP5的访问方式允许限制对类成员的访问. 这是在PHP5中新增的功能,但在许多面向对象语言中都早已存在. 有了访问方式,才能开发一个可靠的面向对象应用程序,并且构建可重用的面向对象类库. 像C++和Java一样,PHP有三种访问方式:public,private和protected. 对于一个类成员的访问方式,可以是其中之一. 如果你没有指明访问方式,默认地访问方式为public. 你也可以为静态成员指明一种访问方式,将访问方式放在static关键字之前(如public static). Public成员可以被毫无限制地访问.类外部的任何代码都可以读写public属性. 你可以从脚本的任何地方调用一个public方法. 在PHP的前几个版本中,所有方法和属性都是public, 这让人觉得对象就像是结构精巧的数组. Private(私有)成员只在类的内部可见. 你不能在一个private属性所在的类方法之外改变或读取它的值. 同样地,只有在同一个类中的方法可以调用一个private方法. 继承的子类也不能访问父类中的private 成员. 要注意,类中的任何成员和类的实例都可以访问private成员. 看例子6.8,equals方法将两个widget进行比较.==运算符比较同一个类的两个对象,但这个例子中每个对象实例都有唯一的ID.equals方法只比较name和price. 注意equals方法如何访问另一个Widget实例的private属性. Java和C都允许这样的操作. Listing 6.8 Private members name = $name; $this->price = floatval($price); $this->id = uniqid(); } //checks if two widgets are the same 检查两个widget是否相同 public function equals($widget) { return(($this->name == $widget->name)AND ($this->price == $widget->price)); } } $w1 = new Widget(Cog, 5.00); $w2 = new Widget(Cog, 5.00); $w3 = new Widget(Gear, 7.00); //TRUE if($w1->equals($w2)) { print("w1 and w2 are the same


n"); } //FALSE if($w1->equals($w3)) { print("w1 and w3 are the same
n"); } //FALSE, == includes id in comparison if($w1 == $w2) //不等,因为ID不同 { print("w1 and w2 are the same
n"); } ?> 如果你对面向对象编程不熟悉,你可能想知道用private成员的目的是什么. 你可以回忆一下封装和耦合的想法,这在本章开头我们有讨论过. Private成员有助于封装数据. 他们可以隐藏在一个类内部而不被类外部的代码接触到. 同时他们还有助于实现松散的耦合. 如果数据结构外的代码不能直接访问内部属性,那么就不会产生一个隐性的关联性. 当然,大部分private属性仍然可以被外部代码共享. 解决方法是用一对public方法,一个是get(获取属性的值),另一个是set(设置属性的值). 构造函数也接受属性的初始值. 这使得成员间的交流通过一个狭窄的,经过良好限定的接口来进行. 这也提供改变传递给方法的值的机会. 注意在例子6.8中,构造函数如何强制使price成为一个float数(floadval()). Protected(受保护的) 成员能被同个类中的所有方法和继承出的类的中所有方法访问到. Public属性有违封装的精神,因为它们允许子类依赖于一个特定的属性来书写.protected方法则不会带来这方面的担忧.一个使用protected方法的子类需要很清楚它的父类的结构才行. 例子6.9由例子6.8改进而得到,包含了一个Widget的子类Thing. 注意Widget现在有一个叫作getName的protected方法. 如果Widget的实例试图调用protected方法将会出错: $w1->getName()产生了一个错误. 但子类Thing中的getName方法可以调用这个protected方法.当然对于证明Widget::getName方法是protected,这个例子显得过于简单. 在实际情况下,使用protected方法要依赖于对对象的内部结构的理解. Listing 6.9 Protected members name = $name; $this->price = floatval($price); $this->id = uniqid(); } //checks if two widgets are the same public function equals($widget) { return(($this->name == $widget->name)AND ($this->price == $widget->price)); } protected function getName() { return($this->name); } } class Thing extends Widget { private $color; public function setColor($color) { $this->color = $color; } public function getColor() { return($this->color); } public function getName() { return(parent::getName()); } } $w1 = new Widget(Cog, 5.00); $w2 = new Thing(Cog, 5.00); $w2->setColor(Yellow); //TRUE (still!) 结果仍然为真 if($w1->equals($w2)) { print("w1 and w2 are the same
n"); } //print Cog 输出 Cog print($w2->getName()); ?> 一个子类可能改变通过覆写父类方法来改变方法的访问方式,尽管如此,仍然有一些限制. 如果你覆写了一个public类成员,他子类中必须保持public. 如果你覆写了一个protected成员,它可保持protected或变成public.Private成员仍然只在当前类中可见. 声明一个与父类的private成员同名的成员将简单地在当前类中建立一个与原来不同的成员. 因此,在技术上你不能覆写一个private成员. Final关键字是限制访问成员方法的另一个方法. 子类不能覆写父类中标识为final的方法. Final关键字不能用于属性. //haohappy注:PHP5的面向对象模型仍然不够完善,如final不像Java中那样对Data,Method甚至Class都可以用.
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 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks 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)

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>Photos to view selected images. Full access – App can view photos

Access metadata of various audio and video files using Python Access metadata of various audio and video files using Python Sep 05, 2023 am 11:41 AM

We can access the metadata of audio files using Mutagen and the eyeD3 module in Python. For video metadata we can use movies and the OpenCV library in Python. Metadata is data that provides information about other data, such as audio and video data. Metadata for audio and video files includes file format, file resolution, file size, duration, bitrate, etc. By accessing this metadata, we can manage media more efficiently and analyze the metadata to obtain some useful information. In this article, we will take a look at some of the libraries or modules provided by Python for accessing metadata of audio and video files. Access audio metadata Some libraries for accessing audio file metadata are - using mutagenesis

How to solve the problem of inaccessibility after Tomcat deploys war package How to solve the problem of inaccessibility after Tomcat deploys war package Jan 13, 2024 pm 12:07 PM

How to solve the problem that Tomcat cannot successfully access the war package after deploying it requires specific code examples. As a widely used Java Web server, Tomcat allows developers to package their own developed Web applications into war files for deployment. However, sometimes we may encounter the problem of being unable to successfully access the war package after deploying it. This may be caused by incorrect configuration or other reasons. In this article, we'll provide some concrete code examples that address this dilemma. 1. Check Tomcat service

How to solve the problem of access denied when modifying files in Windows 7 How to solve the problem of access denied when modifying files in Windows 7 Jul 04, 2023 pm 07:01 PM

How to solve the problem of access denied when modifying files in win7? When modifying some system files, we will often be prompted that we do not have permission to perform the operation. We can turn off the folder permissions or obtain administrator rights. For users who need to modify such files, let’s take a look at the following specific tutorials. Solution to the problem of access denied when modifying files in win7: 1. First select the corresponding folder, click the tool above, and select the folder option. 2. Enter the View tab. 3. Uncheck Use Simple File Sharing and confirm. 4. Then right-click the corresponding folder and click Properties. 5. Enter the Security tab. 6. Select the icon position and click Advanced. 7

How to solve external resource access and calls in PHP development How to solve external resource access and calls in PHP development Oct 08, 2023 am 11:01 AM

How to solve the problem of accessing and calling external resources in PHP development requires specific code examples. In PHP development, we often encounter situations where we need to access and call external resources, such as API interfaces, third-party libraries or other server resources. When dealing with these external resources, we need to consider how to access and call safely while ensuring performance and reliability. This article describes several common solutions and provides corresponding code examples. 1. Use the curl library to call external resources. Curl is a very powerful open source library.

What to do if shared folders cannot be accessed in Windows 10 Home Edition What to do if shared folders cannot be accessed in Windows 10 Home Edition Jan 11, 2024 pm 07:36 PM

Sharing folders is indeed an extremely useful feature in a home or business network environment. It allows you to easily share folders with other users, thereby facilitating file transfer and sharing. Win10 Home Edition shared folder cannot be accessed Solution: Solution 1: Check network connection and user permissions When trying to use Win10 shared folders, we first need to confirm whether the network connection and user permissions are normal. If there is a problem with the network connection or the user does not have permission to access the shared folder, it may result in inaccessibility. 1. First, please ensure that the network connection is smooth so that the computer and the computer where the shared folder is located are in the same LAN and can communicate normally. 2. Secondly check the user permissions to confirm that the current user has permission to share files.

Allow camera device access only in HTML5 Allow camera device access only in HTML5 Sep 22, 2023 pm 11:09 PM

There is no unique access to the camera device in iOS. The official specification recommendation is as follows - User agent implementations of this specification are recommended to ask for user consent before starting to capture content through the microphone or camera. This may be necessary to meet regulatory, legal and best practice requirements related to user data privacy. Additionally, user agent implementations are recommended to provide an indication to the user when an input device is enabled and to enable the user to terminate such capture. Likewise, user agents are recommended to provide user controls, such as allowing the user to select the exact media capture device to use if multiple devices are present. Disable sound capture in video capture mode.

See all articles