search
HomeBackend DevelopmentPHP Tutorial属性和成员变量的概念

属性和成员变量的概念

本来觉得属性和成员变量还是能分清的
直到看了《深入理解Yii2.0》
的第一章节的第一段就凌乱了
http://www.digpage.com/property.html
已附图
求有经验的发开解释下。。
它到底要表达什么。。

回复内容:

属性和成员变量的概念

本来觉得属性和成员变量还是能分清的
直到看了《深入理解Yii2.0》
的第一章节的第一段就凌乱了
http://www.digpage.com/property.html
已附图
求有经验的发开解释下。。
它到底要表达什么。。

按书上的意思

People 有一个 成员变量 age
有一个 属性 年龄

一个是类结构(代码)层面的,一个是语义(逻辑)层面的

=============

我不太赞同上述解释,个人的理解,属性是被暴露(非公开)的成员变量,而成员变量(大部分情况下)应该始终是私有的

Java的例子

<code>class People {
    private Date birthday;   // 生日,成员变量
    public int getAge() {    // 年龄,只读属性
        return daysBetween(birthday, today);  
    }

    private String name;    // 姓名,成员变量
    public String getName() {    // 姓名,读写属性
        return name;
    }
    public void setName(String name) {
        check(name);        // 写校验
        this.name = name;
    }
}                
</code>

属性的读写需要在类中相应的getter/setter进行校验、加工处理等, 以及控制属性是否只读、只写还是可读写

不太贊同 @xelz 的解釋。

實然不推出應然,從屬性與成員變量所通常具有的性質不推出屬性和成員變量應該具有這樣的性質。

換句話說,Java 的例子不能代表普遍意義上的、物件導向程式設計意義上的屬性和成員變量的區別。

要弄清這兩個概念的本質區別,就必須搞清楚它們分別是怎麼來的。

In abstract, property is that which belongs to or with something, whether as an attribute or as a component of said thing.

英文維基百科上說屬性(Property)是某物的品質/標誌或組成部分,這是屬性一詞的本意。

而成員變量(Member variables)則純粹是物件導向的程式設計中的術語,

In object-oriented programming, a member variable (sometimes called a member field) is a variable that is associated with a specific object, and accessible for all its methods (member functions). In class-based languages, these are distinguished into two types: if there is only one copy of the variable shared with all instances of the class, it is called a class variable or static member variable; while if each instance of the class has its own copy of the variable, the variable is called an instance variable.[1]

從物件導向程式設計層面上,成員變量只需是關聯到特定對象的變量,可供成員函數訪問,根本不需要訪問控制作前提,也更不需要成爲私有的。

成員變量可以看作物件導向程式設計的基本要素,是從代碼層面上說的;

而屬性則來自形而上學,是從語義上說的。

具體到不同的特定的物件導向的實現,也有細節上的區別,但萬萬不可以偏概全。

成員變量和屬性是兩個層面的概念,不理解二者的區別,不是缺少開發經驗,而是形而上學基礎太差。

看了截图。。我开始觉得自己就没学好中文。。

  1. 题主 本来能够理解 属性和成员变量。相信并不是不能理解他想表达的意思。
  2. JAVA C#之类的编程语言都有这种 属性 = 成员变量 + 方法
  3. 题主 问的应该是

    比如,我们说People类有一个成员变量 int $age ,表示年龄。那么这里年龄就是属性 , $age 就是成员变量。
    有没有起到完美解答 属性成员变量 的关系。
    我的回答是当然没有,从比如里 我推不出 属性成员变量的关系。但如果看了整个文章,后者理解了属性成员变量的关系来推这个比如。其实也没这个必要了。

  4. 对新手来说,的确很有迷惑性。不过好歹人家后面写了那么多,多少还是能看懂的。

Statement
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
What is dependency injection in PHP?What is dependency injection in PHP?May 07, 2025 pm 03:09 PM

DependencyinjectioninPHPisadesignpatternthatenhancesflexibility,testability,andmaintainabilitybyprovidingexternaldependenciestoclasses.Itallowsforloosecoupling,easiertestingthroughmocking,andmodulardesign,butrequirescarefulstructuringtoavoidover-inje

Best PHP Performance Optimization TechniquesBest PHP Performance Optimization TechniquesMay 07, 2025 pm 03:05 PM

PHP performance optimization can be achieved through the following steps: 1) use require_once or include_once on the top of the script to reduce the number of file loads; 2) use preprocessing statements and batch processing to reduce the number of database queries; 3) configure OPcache for opcode cache; 4) enable and configure PHP-FPM optimization process management; 5) use CDN to distribute static resources; 6) use Xdebug or Blackfire for code performance analysis; 7) select efficient data structures such as arrays; 8) write modular code for optimization execution.

PHP Performance Optimization: Using Opcode CachingPHP Performance Optimization: Using Opcode CachingMay 07, 2025 pm 02:49 PM

OpcodecachingsignificantlyimprovesPHPperformancebycachingcompiledcode,reducingserverloadandresponsetimes.1)ItstorescompiledPHPcodeinmemory,bypassingparsingandcompiling.2)UseOPcachebysettingparametersinphp.ini,likememoryconsumptionandscriptlimits.3)Ad

PHP Dependency Injection: Boost Code MaintainabilityPHP Dependency Injection: Boost Code MaintainabilityMay 07, 2025 pm 02:37 PM

Dependency injection provides object dependencies through external injection in PHP, improving the maintainability and flexibility of the code. Its implementation methods include: 1. Constructor injection, 2. Set value injection, 3. Interface injection. Using dependency injection can decouple, improve testability and flexibility, but attention should be paid to the possibility of increasing complexity and performance overhead.

How to Implement Dependency Injection in PHPHow to Implement Dependency Injection in PHPMay 07, 2025 pm 02:33 PM

Implementing dependency injection (DI) in PHP can be done by manual injection or using DI containers. 1) Manual injection passes dependencies through constructors, such as the UserService class injecting Logger. 2) Use DI containers to automatically manage dependencies, such as the Container class to manage Logger and UserService. Implementing DI can improve code flexibility and testability, but you need to pay attention to traps such as overinjection and service locator anti-mode.

What is the difference between unset() and session_destroy()?What is the difference between unset() and session_destroy()?May 04, 2025 am 12:19 AM

Thedifferencebetweenunset()andsession_destroy()isthatunset()clearsspecificsessionvariableswhilekeepingthesessionactive,whereassession_destroy()terminatestheentiresession.1)Useunset()toremovespecificsessionvariableswithoutaffectingthesession'soveralls

What is sticky sessions (session affinity) in the context of load balancing?What is sticky sessions (session affinity) in the context of load balancing?May 04, 2025 am 12:16 AM

Stickysessionsensureuserrequestsareroutedtothesameserverforsessiondataconsistency.1)SessionIdentificationassignsuserstoserversusingcookiesorURLmodifications.2)ConsistentRoutingdirectssubsequentrequeststothesameserver.3)LoadBalancingdistributesnewuser

What are the different session save handlers available in PHP?What are the different session save handlers available in PHP?May 04, 2025 am 12:14 AM

PHPoffersvarioussessionsavehandlers:1)Files:Default,simplebutmaybottleneckonhigh-trafficsites.2)Memcached:High-performance,idealforspeed-criticalapplications.3)Redis:SimilartoMemcached,withaddedpersistence.4)Databases:Offerscontrol,usefulforintegrati

See all articles

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor