Summary of PHP object-oriented essence, PHP object-oriented essence_PHP tutorial

WBOY
Release: 2016-07-13 10:14:44
Original
985 people have browsed it

Summary of PHP object-oriented essence, PHP object-oriented essence

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.

Copy code The code is as follows:
class MyClass {
const CONST_VALUE = 'A constant value';
}

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.

Copy code The code is as follows:
private static $firstCount = 0;
private $lastCount;

//Constructor
function __construct()
{
$this->lastCount = ++self:$firstCount; //Use self to call static variables. When calling self, you must use:: (field operation symbol)
}


parent: Indicates the scope of the parent class of the current class, and the rest is the same as the self attribute. parent is a pointer to the parent class. Generally, we use parent to call the constructor of the parent class.
Copy code The code is as follows:
//Constructor of inherited class
function __construct( $personSex, $personAge )
{
parent::__construct( "test" ); //Use parent to call the constructor of the parent class
            $this->personSex = $personSex;
             $this->personAge = $personAge;
}

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

父类 子类 结果
有构造函数 无构造函数 父构造
有构造函数 有构造函数 子构造


8 Interfaces

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.

Copy code The code is as follows:
// Declare an 'iTemplate' interface
interface iTemplate
{
Public function setVariable($name, $var);
Public function getHtml($template);
}
// Implement interface
// The following writing is correct
class Template implements iTemplate
{
Private $vars = array();

Public function setVariable($name, $var)
{
            $this->vars[$name] = $var;
}

Public function getHtml($template)
{
foreach($this->vars as $name => $value) {
$template = str_replace('{' . $name . '}', $value, $template);
}

          return $template;
}
}

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

Copy code The code is as follows:
class Person{
//The following are the member attributes of people
private $name; //Person’s name
private $sex; //person’s gender
private $age; //Age of person
//__get() method is used to obtain private attributes
private function __get($property_name){
if(isset($this->$property_name)){
return($this->$property_name);}else {
return(NULL);
}
}
}
//__set() method is used to set private attributes
private function __set($property_name, $value){
$this->$property_name = $value;
}
//__isset() method
private function __isset($nm){
echo "When the isset() function determines a private member, it is automatically called
";
return isset($this->$nm);
}
//__unset() method
private function __unset($nm){
echo "Automatically called when the unset() function is used outside the class to delete private members
";
unset($this->$nm);
}
}
$p1=new Person();
$p1->name="this is a person name";
//When using the isset() function to measure private members, the __isset() method is automatically called to help us complete it, and the return result is true
echo var_dump(isset($p1->name))."
";
echo $p1->name."
";
//When using the unset() function to delete private members, the __unset() method is automatically called to help us complete the task and delete the name private attribute
unset($p1->name);
//It has been deleted, so there will be no output for this line
echo $p1->name;
?>

Copy code The code is as follows:
class Person{
//The following are the member attributes of people
private $name;
//Person’s name
private $sex;
//Person’s gender
private $age;
//Age of person
//__get() method is used to obtain private attributes
private function __get($property_name){
if(isset($this->$property_name)){
return($this->$property_name);
}else{
return(NULL);
}
}
}
//__set() method is used to set private attributes
private function __set($property_name, $value){
$this->$property_name = $value;
}
//__isset() method
private function __isset($nm){
echo "When the isset() function determines a private member, it is automatically called
";
return isset($this->$nm);
}
//__unset() method
private function __unset($nm){
echo "Automatically called when the unset() function is used outside the class to delete a private member
";
unset($this->$nm);
}
}
$p1=new Person();
$p1->name="this is a person name";
//When using the isset() function to measure private members, the __isset() method is automatically called to help us complete it, and the return result is true
echo var_dump(isset($p1->name))."
";
echo $p1->name."
";
//When using the unset() function to delete private members, the __unset() method is automatically called to help us complete the task and delete the name private attribute
unset($p1->name);
//It has been deleted, so there will be no output for this line
echo $p1->name;
?>

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.

How to understand PHP object-oriented?

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

php object-oriented

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/

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/907841.htmlTechArticleSummary of PHP object-oriented essentials, PHP object-oriented essence This article summarizes the essence of PHP object-oriented programming with examples . Share it with everyone for your reference. The specific analysis is as follows: 1 Use exten...
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 Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template