面向对象编程的基本原则:
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;
用以上方法设置属性值会有很多问题:
第一:PHP允许动态设置属性,如果拼错或忘记属性名时并不会得到警告。例如错误地把
<span>$product1</span>->producterMainName = "Willa";
写作
<span>$product1</span>->producterSecondName = "Willa";
,当我们输出作者名字的时候,会有意想不到的结果。
第二:类太过松散,我们没有强制设置标题、价格或者产品名称,客户端代码可以确定的是这些属性存在,但是面对的可能是默认值也可能不是,理想情况下,我们希望实例化ShopProduct对象时设置有意义的属性值。
第三:不得不重复做一些经常做的事,比如多次需要完整输出作者的名字,就要重复使用
<span>echo</span> 'author: '.<span>$product1</span>->producterFirstName.' '.<span>$product1</span>->producterMainName;