Home > Article > Backend Development > php object-oriented programming, php object-oriented_PHP tutorial
Basic principles of object-oriented programming:
1. Set the attributes of the class
<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;
There are many problems with setting attribute values using the above method:
First: PHP allows you to set attributes dynamically, and you will not get a warning if you misspell or forget the attribute name. For example, incorrectly placing
<span>$product1</span>->producterMainName = "Willa";
Writing
<span>$product1</span>->producterSecondName = "Willa";
, when we output the author's name, there will be unexpected results.
Second: The class is too loose. We do not force the setting of title, price or product name. The client code can be sure that these attributes exist, but it may or may not be the default value. Ideally, we You want to set meaningful property values when instantiating a ShopProduct object.
Third: You have to do something you do frequently, such as if you need to output the author’s name in full multiple times, you have to reuse it
<span>echo</span> 'author: '.<span>$product1</span>->producterFirstName.' '.<span>$product1</span>->producterMainName;