属性和成员变量的概念

WBOY
Release: 2016-06-06 20:38:24
Original
1091 people have browsed it

属性和成员变量的概念

本来觉得属性和成员变量还是能分清的
直到看了《深入理解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>
Copy after login

属性的读写需要在类中相应的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. 对新手来说,的确很有迷惑性。不过好歹人家后面写了那么多,多少还是能看懂的。

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!