Home > php教程 > php手册 > body text

php面向对象编程,php面向对象

WBOY
Release: 2016-06-13 08:44:42
Original
1464 people have browsed it

php面向对象编程,php面向对象

面向对象编程的基本原则:

  • 单一职责:一个类,只需要做好一件事
  • 开放封闭:一个类,应该是可扩展的,而不是可修改的
  • 依赖倒置:一个类,不应该强依赖另一个类。每个类对应另外一个类都是可替换的
  • 配置化:尽可能地使用配置,而不是硬编码
  • 面向接口编程:只需要关心接口,不需要关心实现

 1、设置类的属性

<span>class</span><span> ShopProduct {
    </span><span>public</span> <span>$title</span> = 'default product'<span>;
    </span><span>public</span> <span>$producterMainName</span> = 'main name'<span>;
    </span><span>public</span> <span>$producterFirstName</span> = 'first name'<span>;
    </span><span>public</span> <span>$price</span> = 0<span>;
}

</span><span>$product1</span> = <span>new</span><span> ShopProduct();

</span><span>//</span><span>设置属性</span>
<span>$product1</span>->title = "My Antonia"<span>;
</span><span>$product1</span>->producterFirstName = "Cather"<span>;
</span><span>$product1</span>->producterMainName = "Willa"<span>;
</span><span>$product1</span>->price = 5.99<span>;

</span><span>//</span><span>访问</span>
<span>echo</span> 'author: '.<span>$product1</span>->producterFirstName.' '.<span>$product1</span>->producterMainName;
Copy after login

用以上方法设置属性值会有很多问题:

第一:PHP允许动态设置属性,如果拼错或忘记属性名时并不会得到警告。例如错误地把

<span>$product1</span>->producterMainName = "Willa";
Copy after login

写作

<span>$product1</span>->producterSecondName = "Willa";
Copy after login

,当我们输出作者名字的时候,会有意想不到的结果。

第二:类太过松散,我们没有强制设置标题、价格或者产品名称,客户端代码可以确定的是这些属性存在,但是面对的可能是默认值也可能不是,理想情况下,我们希望实例化ShopProduct对象时设置有意义的属性值。

第三:不得不重复做一些经常做的事,比如多次需要完整输出作者的名字,就要重复使用

<span>echo</span> 'author: '.<span>$product1</span>->producterFirstName.' '.<span>$product1</span>->producterMainName;
Copy after login

 

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 Recommendations
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!