Php object-oriented programming, php object-oriented. Php object-oriented programming, the basic principle of php object-oriented programming: a single responsibility: a class, only one thing to do is open and closed: a class should be scalable, php object-oriented programming and php object-oriented
Basic principles of object-oriented programming:
- Single responsibility: one class, only one thing needs to be done
- Open and closed: a class should be extensible, rather than changeable.
- Dependency Inversion: one class should not be highly dependent on another class. Each class corresponds to another class which is replaceable.
- Configuration: Use configuration as much as possible, instead of hard coding
- Interface-Oriented Programming: you only need to care about interfaces, and do not need to care about implementation.
1. set class attributes
Class ShopProduct {public $ title = 'default product'; public $ producterMainName = 'main name'; public $ producterFirstName = 'first name'; public $ price = 0 ;} $ product1 = new ShopProduct (); // Set attributes $ product1-> title = "My major IA"; $ product1-> producterFirstName = "Cather "; $ product1-> producterMainName = "Willa"; $ product1-> price = 5.99; // access echo 'Author :'. $ product1-> producterFirstName. ''. $ product1-> producterMainName;
Setting attribute values using the preceding method has many problems:
First, PHP allows dynamic attribute setting. if the attribute name is misspelled or forgotten, no warning is given. For example
$product1->producterMainName = "Willa";
Writing
$product1->producterSecondName = "Willa";
When we output the author's name, there will be unexpected results.
Second, the class is too loose. we have not set the title, price, or product name forcibly. what the client code can determine is that these attributes exist, but the default values may not exist, ideally, we want to set meaningful attribute values when instantiating a ShopProduct object.
Third, you have to repeat some things that you often do. for example, if you need to output the author's name multiple times, you must repeat it.
echo 'author: '.$product1->producterFirstName.' '.$product1->producterMainName;
The basic principle of objective object-oriented programming: a single responsibility: a class, you only need to do one thing open and closed: a class, should be scalable, and...