Home > Article > Backend Development > Summary of PHP object-oriented essence, PHP object-oriented essence_PHP tutorial
The examples in this article summarize the essence of PHP object-oriented programming. Share it with everyone for your reference. The specific analysis is as follows:
1 Use extends to implement inheritance and the meaning of overloading and magic methods
class B extends A
When declaring, B does not need to have the method in A
When calling:
$b=new B();
$b->Method() in A;
$b->Attributes in A=1;
$b->Method() in B;
$b->Method() in B;
If $a=new A();
Yes
$a->Method() in A;
$a->Attributes in A=1;
Not possible
$a->Method() in B;
$a->Method() in B;
Overloading: B inherits A, and B implements the method attribute with the same name as A.
"Overloading" in PHP is different from most other object-oriented languages. Traditional "overloading" is used to provide multiple class methods with the same name, but each method has different parameter types and numbers.
Magic methods: PHP treats all class methods starting with __ (two underscores) as magic methods. So when you define your own class methods, do not prefix them with __.
2 Inherit the visibility of private and protected access modifiers
Attribute methods private cannot be inherited
The attribute method protected class is not visible outside and can be inherited
Class members defined by public property methods can be accessed from anywhere
3 Applications of double colon:: in php
The "::" operator is often seen in PHP class codes. This is a scope limiting operator, which is represented by a double colon "::". It is used to set the levels of different scopes in the class. The left side is the scope and the right side is the members of the access scope.
There are two scopes defined in PHP: self and parent (static scope is provided in PHP6).
The scope resolution operator (also known as Paamayim Nekudotayim) or more simply a pair of colons can be used to access static members, methods and constants, and can also be used by subclasses to override members and methods in parent classes.
echo MyClass::CONST_VALUE;
class OtherClass extends MyClass
{
Public static $my_static = 'static var';
public static function doubleColon() {
echo parent::CONST_VALUE . "n";
echo self::$my_static . "n";
}
}
OtherClass::doubleColon();
//Subclass overrides parent class
class MyClass
{
protected function myFunc() {
echo "MyClass::myFunc()n";
}
}
class OtherClass extends MyClass
{
// Override the method in the parent class
Public function myFunc()
{
//But the overridden method can still be called
parent::myFunc();
echo "OtherClass::myFunc()n";
}
}
$class = new OtherClass();
$class->myFunc();
4 The role of this, self and parent in php
this: It is a pointer to the current object instance and does not point to any other object or class.
self: represents the scope of the current class. Unlike this, it does not represent a specific instance of the class. Self cannot be used in code outside the class, and it cannot identify its own position in the hierarchy of inheritance. That is to say, when self is used in an extended class, it does not call the method of the parent class, but the overloaded method of the extended class. Self points to the class itself, that is, self does not point to any instantiated object. Generally, self is used to point to static variables in the class.
//Constructor
function __construct()
{
$this->lastCount = ++self:$firstCount; //Use self to call static variables. When calling self, you must use:: (field operation symbol)
}
5 Constructor and destructor
A class with a constructor will call this method first every time an object is created, so it is very suitable to do some initialization work before using the object.
function __construct() {}
If a constructor is defined in a subclass, the constructor of its parent class will not be implicitly called. To execute the parent class's constructor, you need to call parent::__construct() in the child class's constructor.
PHP 5 introduced the concept of destructors, similar to other object-oriented languages such as C++. A destructor is executed when all references to an object are removed or when the object is explicitly destroyed.
function __destruct() {}
6 final keywords
PHP 5 adds a new final keyword. If a method in the parent class is declared final, the subclass cannot override the method; if a class is declared final, it cannot be inherited.
7 Inheritance and Constructor
父类 | 子类 | 结果 |
有构造函数 | 无构造函数 | 父构造 |
有构造函数 | 有构造函数 | 子构造 |
You can define an interface through interface, just like defining a standard class.
Note:
1) But all the methods defined in it are empty;
2) All methods defined in the interface must be public, which is a characteristic of the interface;
3) When implementing multiple interfaces, methods in the interfaces cannot have the same name;
4) Interfaces can also be inherited by using the extends operator;
5) Constants can also be defined in the interface. Interface constants and class constants are used exactly the same. They are all fixed values and cannot be modified by subclasses or subinterfaces.
9 attributes
The variable members of the class are called "properties". The property declaration starts with the keywords public or protected or private, and is followed by a variable. Variables in attributes can be initialized, but the initialized value must be a constant. The constant here refers to the constant that the PHP script is in the compilation stage, not the constant calculated in the running stage after the compilation stage.
In PHP5, two functions "__get()" and "__set()" are predefined to obtain
Get and assign its attributes, as well as "__isset()" to check attributes and "__unset()" to delete attributes.
To put it simply, one is for obtaining value and the other is for assigning value. , the two methods "__set()" and "__get()", these two methods do not exist by default, but are manually added to the class. Like the constructor method (__construct()), they are added to the class. will exist. You can add these two methods in the following way. Of course, you can also add them according to your personal style: //__get() method is used to obtain private attributes
10 clones
Object copying can be completed through the clone keyword (if the __clone() method exists in the object, it will be called first). The __clone() method in an object cannot be called directly.
When an object is copied, PHP5 will perform a "shallow copy" of all properties of the object. All references in the properties remain unchanged and point to the original variables. If the __clone() method is defined, the __clone() method in the newly created object (the object generated by copying) will be called and can be used to modify the value of the attribute (if necessary).
I hope this article will be helpful to everyone’s PHP object-oriented programming.
OOP thinking MVC structure, you only need to understand what M V C means respectively. The simplest understanding is that what content needs to be displayed on the view page is handed over to controll for processing. What data does controll need? MODEL provides it for database processing and then all is fed back to controll. After the processing is completed, Transfer all the content to the view for page display
To put it simply, the view is used to display the controll and is used to control and process the model for database analysis and processing
OOP thinking is actually simply to treat everything of the same type as a container , and then process it centrally, process the data through the interface and then feed it back to the page
Basic class for PHP to operate mysql database, object-oriented with annotations. It also adds some additional functions: insert data into the specified table function insertData($dbname,$data)
ServerName, UserName, PassWord, DBName. These parameters use
define(“UserName”, “?? ”); //Database connection username
define(“PassWord”, “??”); //Database connection password
define(“ServerName”, “??”); //Name of the database server
define("DBName","??"); //Database name
/**
* Function: Insert data into the specified table
* Parameter: $dbname table name ,$data array (format: $data['field name'] = value)
* Return: insert record id
*/
public function insertData($dbname,$data)
{
$field = implode(',',array_keys($data)); //Define the field part of the sql statement
$i = 0;
foreach($data as $key => $val) //Combine the value part of the sql statement
{
$value.= "'" . $val . "'";
if($i < count($data) - 1) //Judge Whether to the last value of the array
$value.= ",";
$i++;
}
$sql = "INSERT INTO " . $dbname . " (" . $field . " ) VALUES(" . $value . ")";
return $this->insert($sql);
}
See the reference for the rest. Also note that if The encoding you are using is not utf8. You need to modify this line mysql_query("set names utf8"); //Also limit the encoding type!
mysql_query("set names gbk"); //gbk encoding type!
or
mysql_query("set names gb2312"); //Also limit the encoding type!
For additional questions: It is possible to combine them to make SQL statements, but it is recommended that if you are not familiar with php and sql, it is best to write them separately. There is no need to spend a lot of time for a small function. Except for more complex insertions!
Reference material: ruyihe.com/blog/2010/10/php basic class for operating mysql database, object-oriented with annotations/