PHP object-oriented summary, php object-oriented essentials _ PHP Tutorial

Source: Internet
Author: User
PHP object-oriented needs to be summarized, and php object-oriented needs. PHP object-oriented needs to be summarized, php object-oriented needs this article examples summarize the essence of PHP object-oriented programming. Share it with you for your reference. The specific analysis is as follows: 1. use exten PHP object-oriented methods to summarize, and php object-oriented methods

This example summarizes the essentials of PHP object-oriented programming. Share it with you for your reference. The specific analysis is as follows:

1. use extends to implement inheritance and the meanings of the overloaded and magic methods

Class B extends
The method in A can be absent from B during declaration.
When calling:

$ B = new B ();
$ B-> method () in ();
$ B-> attribute in A = 1;
$ B-> method () in B ();
$ B-> method () in B ();

If $ a = new ();
Yes
$ A-> method () in ();
$ A-> attribute in A = 1;
No
$ A-> method () in B ();
$ A-> method () in B ();

Overload: B inherits the method attributes with the same name as A in A and B.
PHP's "overload" is different from most other object-oriented languages. The traditional "overload" is used to provide multiple class methods with the same name, but the parameter types and numbers of each method are different.

Magic method: PHP treats all class methods starting with _ (two underscores) as magic methods. Therefore, when you define your own class methods, do not use _ as the prefix.

2 inherit the access modifier visibility with private and protected

Attribute method private cannot be inherited
Property method: the protected class is invisible and can be inherited.
The class members defined by the attribute method public can be accessed anywhere.

3. application of double colon: in php

In php code, we often see the ":" operator, which is a limited scope operator. it is represented by a double colon ":", which is used to pin the levels of different scopes in the class. On the left is the access scope member on the right of the scope.
The scope defined in php is self and parent (static scope is provided in php6 ).

The range resolution operator (also known as Paamayim nekudow.im) or, more simply, a colon can be used to access static members, methods, and constants. It can also be used to override members and methods in the parent class by subclass.

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 overwrites the parent class
Class MyClass
{
Protected function myFunc (){
Echo "MyClass: myFunc () \ n ";
}
}

Class OtherClass extends MyClass
{
// Override the methods in the parent class
Public function myFunc ()
{
// But you can still call the overwritten method
Parent: myFunc ();
Echo "OtherClass: myFunc () \ n ";
}
}

$ Class = new OtherClass ();
$ Class-> myFunc ();

4. roles of this, self, and parent in php

This is the pointer to the current object instance, and does not point to any other object or class.
Self: indicates the scope of the current class. Unlike this, self does not represent a specific instance of the class and cannot be used in code outside the class, in addition, it cannot identify its position in the hierarchy of inheritance. That is to say, when self is used in an extension class, it calls not the method of the parent class, but the method of overloading the extension class. Self points to the class itself, that is, self does not point to any instantiated object. Generally, self points to static variables in the class.

The code is as follows:

Private static $ firstCount = 0;
Private $ lastCount;

// Constructor
Function _ construct ()
{
$ This-> lastCount = + self: $ firstCount; // to use self to call static variables, you must use: (domain operator number)
}


Parent: indicates the scope of the current class parent class, and the rest are the same as the self feature. Parent is a pointer to the parent class. generally, we use parent to call the constructor of the parent class.

The code is as follows:

// Constructor of the inherited class
Function _ construct ($ personSex, $ personAge)
{
Parent: :__ construct ("test"); // uses parent to call the constructor of the parent class.
$ This-> personSex = $ personSex;
$ This-> personAge = $ personAge;
}

5. constructor and Destructor

Classes with constructors call this method each time an object is created, so it is very suitable for initialization before using the object.
Function _ construct (){}
If the constructor is defined in the subclass, the constructor of its parent class will not be called secretly. To execute the constructor of the parent class, you must call parent ::__ construct () in the constructor of the subclass ().
PHP 5 introduces the concept of destructor, which is similar to other object-oriented languages, such as C ++. The Destructor is executed when all references to an object are deleted or when the object is explicitly destroyed.
Function _ destruct (){}

6 final keywords

PHP 5 adds a final keyword. If the method in the parent class is declared as final, the subclass cannot overwrite the method. if a class is declared as final, it cannot be inherited.

7. Inheritance and constructor

Parent class Subclass Result
Constructor No constructor Parent structure
Constructor Constructor Sub-structure


8 interfaces

You can use interfaces to define an interface, just like defining a standard class.
Note:
1) but all the methods defined in the definition are empty;
2) all methods defined in the interface must be public, which is a feature of the interface;
3) when multiple interfaces are implemented, the methods in the interfaces cannot have duplicate names;
4) interfaces can also be inherited by using the extends operator;
5) constants can also be defined in the interface. The use of interface constants and class constants is identical. They are all set values and cannot be modified by the quilt class or subinterface.

The code is as follows:

// Declare an 'itemplate 'interface
Interface iTemplate
{
Public function setVariable ($ name, $ var );
Public function getHtml ($ template );
}
// Implementation interface
// The following statements are 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 member of the class is called "attribute". The attribute declaration starts with the keyword "public", "protected", or "private", and then comes with a variable. The variables in the property can be initialized, but the initialization value must be a constant. the constant here means that the php script is a constant during compilation, instead of the constant calculated in the running phase after the compilation phase.
In PHP5, the two functions "_ get ()" and "_ set ()" are predefined to obtain
Take and assign values to its attributes, and check the attribute "_ isset ()" and the method "_ unset ()" for deleting the attribute ()".
In short, one is a value, and the other is a value ., The "_ set ()" and "_ get ()" methods do not exist by default, but are manually added to the class, like the constructor (_ construct (), the class will only exist after it is added. you can add these two methods in the following way. of course, you can also add them in your own style: // _ get () is used to obtain private attributes.

The code is as follows:

<? Php
Class Person {
// The following are the member attributes of a person.
Private $ name; // The name of a person.
Private $ sex; // gender of a person
Private $ age; // age of a person
// _ Get () is used to obtain private attributes.
Private function _ get ($ property_name ){
If (isset ($ this-> $ property_name )){
Return ($ this-> $ property_name);} else {
Return (NULL );
}
}
}
// _ Set () is used to set private attributes.
Private function _ set ($ property_name, $ value ){
$ This-> $ property_name = $ value;
}
// _ Isset () method
Private function _ isset ($ nm ){
When the echo "isset () function is used to determine private members, 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 the isset () function is used to determine a private member, the _ isset () method is automatically called to help us complete the measurement. the returned result is true.
Echo var_dump (isset ($ p1-> name ))."
";
Echo $ p1-> name ."
";
// When the unset () function is used to delete a private member, the _ unset () method is automatically called to help us complete the deletion.
Unset ($ p1-> name );
// The row has been deleted and no output exists.
Echo $ p1-> name;
?>

The code is as follows:

<? Php
Class Person {
// The following are the member attributes of a person.
Private $ name;
// Name of the person
Private $ sex;
// Gender of a person
Private $ age;
// Age of the person
// _ Get () is used to obtain private attributes.
Private function _ get ($ property_name ){
If (isset ($ this-> $ property_name )){
Return ($ this-> $ property_name );
} Else {
Return (NULL );
}
}
}
// _ Set () is used to set private attributes.
Private function _ set ($ property_name, $ value ){
$ This-> $ property_name = $ value;
}
// _ Isset () method
Private function _ isset ($ nm ){
When the echo "isset () function is used to determine private members, 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 the isset () function is used to determine a private member, the _ isset () method is automatically called to help us complete the measurement. the returned result is true.
Echo var_dump (isset ($ p1-> name ))."
";
Echo $ p1-> name ."
";
// When the unset () function is used to delete a private member, the _ unset () method is automatically called to help us complete the deletion.
Unset ($ p1-> name );
// The row has been deleted and no output exists.
Echo $ p1-> name;
?>

10 clone

Object replication can be completed by using the clone keyword (if the _ clone () method exists in the object, it will be called first ). The _ clone () method in the object cannot be called directly.
After an object is copied, PHP5 performs a shallow copy operation on all attributes of the object ). The references in all attributes remain unchanged and point to the original variables. If the _ clone () method is defined, the _ clone () method in the newly created object (copying the generated object) will be called, can be used to modify the attribute value (if necessary ).

I hope this article will help you with php object-oriented programming.


How does php target users?

OOP: MVC structure you can understand what m v c represents. the simplest understanding is that the view page needs to display the content to controll for processing, what data MODEL does controll need for database processing? then, all data is fed back to controll. after processing, all data is forwarded to the view page for display.

Simply put, the view is used to display the controll to control the processing model for database analysis and processing.
In fact, the OOP idea simply regards all of the same type as a container and then processes the data in a centralized manner. The interface is used to process the data and then the data is fed back to the page.

Php object-oriented

The basic class for PHP to operate mysql databases, with object-oriented annotations. Some other functions are added: insert data function insertData ($ dbname, $ data) into the specified table)
ServerName, UserName, PassWord, DBName
Define ("UserName", "?"); // Database connection username
Define ("PassWord", "?"); // Database connection password
Define ("ServerName", "?"); // Database server name
Define ("DBName ","??"); // Database name

/**
* Function: insert data into a specified table
* Parameter: $ dbname table name, $ data array (format: $ data ['Field name'] = value)
* Return value: the id of the inserted record.
*/
Public function insertData ($ dbname, $ data)
{
$ Field = implode (',', array_keys ($ data); // defines the fields of an SQL statement.
$ I = 0;
Foreach ($ data as $ key => $ val) // combines the values of SQL statements
{
$ Value. = "'". $ val ."'";
If ($ I <count ($ data)-1) // determines whether the last value of the array exists.
$ Value. = ",";
$ I ++;
}
$ SQL = "INSERT INTO". $ dbname. "(". $ field. ") VALUES (". $ value .")";
Return $ this-> insert ($ SQL );
}

For the rest of the code, see the reference. Also, if the encoding you are using is not utf8, you need to modify this line of mysql_query ("set names utf8"); // specify the encoding type!
Mysql_query ("set names gbk"); // gbk encoding type!
Or
Mysql_query ("set names gb2312"); // specify the encoding type!

Supplementary question: we can combine SQL statements. However, we recommend that you write SQL statements separately if you are not familiar with php and SQL. you do not need to spend a lot of time on a small function. Except for complicated inserts!
Reference: ruyihe.com/blog/2010/10/php: Basic class for operating the mysqldata database, which can be explained to the object/

Examples in this article summarize the essentials of PHP object-oriented programming. Share it with you for your reference. The specific analysis is as follows: 1 use exten...

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.