PHP object-oriented Essentials Summary _php Tips

Source: Internet
Author: User
Tags php class shallow copy vars

This article summarizes the essentials of object-oriented Programming in PHP. Share to everyone for your reference. The specific analysis is as follows:

1 implementing inheritance with extends and the meaning of overloading and magic methods

Class B extends A
In the statement, B can have no method in a.
The time of the call:

$b =new B ();
The method of $b->a ();
The attribute in the $b->a = 1;
The method of $b->b ();
The method of $b->b ();

If $a=new a ();
OK
The method of $a->a ();
The attribute in the $a->a = 1;
No
The method of $a->b ();
The method of $a->b ();

Overload: B inherits the method properties in a, B, and the same name as a.
"Overload" in PHP is different from most other object-oriented languages. Traditional "overloads" are used to provide multiple class methods with the same name, but each method has a different parameter type and number.

Magic Method: Php as a magic method of all the class methods that start with __ (two underscores). So when you define your own class method, don't prefix it with __.

2 inheritance with private and protected access modifier visibility

Property method private cannot be inherited
Property methods are not visible outside the protected class and can be inherited
Property method public defines a class member that can be accessed anywhere

3 PHP Double colon:: Application

PHP class code often see "::" operator, this is scoped operator, is a double colon "::" to indicate that it is used to top the different scopes in the class level. To the left is the right side of the scope that is the member that accesses the scope.
The scope defined in PHP is self and parent two (a static scope is provided in PHP6).

The range 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 it can be used to overwrite members and methods in the parent class.

Copy Code code 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::d Oublecolon ();
Subclass Overrides Parent class
Class MyClass
{
protected function MyFunc () {
echo "Myclass::myfunc () \ n";
}
}

Class Otherclass extends MyClass
{
Overriding methods in the parent class
Public Function MyFunc ()
{
But you can still invoke methods that have been overridden
Parent::myfunc ();
echo "Otherclass::myfunc () \ n";
}
}

$class = new Otherclass ();
$class->myfunc ();

4 The role of this and self and parent in PHP

This 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 particular instance of a class, cannot use self in code other than a class, and it does not recognize its position in the hierarchy of inheritance. That is, when you use self in an extension class, it calls not the method of the parent class, but the method that extends the overload of the class. Self is pointing to the class itself, that is, self does not point to any object that has already been instantiated, and general self uses it to point to static variables in the class.

Copy Code code as follows:
private static $firstCount = 0;
Private $lastCount;

Constructors
function __construct ()
{
$this->lastcount = ++self: $firstCount; Use self to invoke a static variable that must be invoked using the Self::(field operator symbol)
}


Parent: Represents the scope of the current class's parent class, and the rest is the same as the self attribute. Parent is a pointer to a parent class, in general we use parent to invoke the constructor of the parent class.
Copy Code code as follows:
Constructors for inheriting classes
function __construct ($personSex, $personAge)
{
Parent::__construct ("test"); The constructor of the parent class was called using parent
$this->personsex = $personSex;
$this->personage = $personAge;
}

5 constructor functions and destructors

Classes with constructors Call this method the first time you create an object, so it is ideal to do some initialization before using the object.
function __construct () {}
If a constructor is defined in a subclass, it does not implicitly invoke the constructor of its parent class. To execute the constructor of the parent class, you need to call Parent::__construct () in the constructor of the subclass.
PHP 5 introduces the concept of destructors, which is similar to other object-oriented languages, such as C + +. Destructors are executed when all references to an object are deleted or when an object is explicitly destroyed.
function __destruct () {}

6 Final keyword

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

7 inheritance and constructors

Parent class Sub Class Results
Have constructors No constructors Parent constructs
Have constructors Have constructors Child constructs


8 Interface

You can define an interface by interface, just as you would define a standard class.
Attention:
1) But all the methods defined therein are empty;
2 All methods defined in the interface must be public, which is the characteristic of the interface;
3 When implementing multiple interfaces, the methods in the interface cannot have duplicate names;
4 The interface can also be inherited by using the extends operator;
5 The 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 quilts or sub-interfaces.

Copy Code code as follows:
Declare a ' ITemplate ' interface
Interface ITemplate
{
Public Function SetVariable ($name, $var);
Public Function gethtml ($template);
}
Implementing interfaces
The following is the correct wording
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 Properties

A variable member of a class is called a property, and the property declaration is made up of the keyword public or protected or private, and then a variable. A variable in a property can be initialized, but the initialized value must be a constant, where the constants are constants when the PHP script is compiled, not the constants that are calculated at run time after the compile phase.
In PHP5, two functions are predefined "__get ()" and "__set ()" To obtain
Fetch and assign its properties, and check the __isset () of the property and the Method "__unset ()" that deletes the property.
Simply put, one is the value, the other is the assignment. , "__set ()" and "__get ()" Two methods, these two methods do not exist by default, but instead we add them by hand to the class, like the construction Method (__construct ()), the class is added to exist, you can add the two methods in the following way. Of course, it can be added as a personal style: the//__get () method is used to get private properties

Copy Code code as follows:
<?php
Class person{
The following are the member properties of the person
Private $name; Person's name
Private $sex; The gender of the person
Private $age; The age of the person
__get () method to get private property
Private Function __get ($property _name) {
if (Isset ($this-> $property _name)) {
Return ($this-> $property _name); else {
return (NULL);
}
}
}
The __set () method is used to set private properties
Private Function __set ($property _name, $value) {
$this-> $property _name = $value;
}
__isset () method
Private Function __isset ($NM) {
The echo "Isset () function, when determining private members, automatically invokes <br>";
return Isset ($this-> $nm);
}
__unset () method
Private Function __unset ($NM) {
echo "<br>" automatically invoked when using the unset () function outside the class to delete private members;
unset ($this-> $nm);
}
}
$p 1=new person ();
$p 1->name= "This was a person name";
When you use the Isset () function to determine a private member, the __isset () method is automatically invoked to help us complete, returning the result to True
Echo Var_dump (Isset ($p 1->name)). " <br> ";
echo $p 1->name. " <br> ";
When you delete a private member using the unset () function, the __unset () method is automatically invoked to help us complete, delete the name private property
unset ($p 1->name);
has been deleted, and there is no output for this line.
Echo $p 1->name;
?>

Copy Code code as follows:
<?php
Class person{
The following are the member properties of the person
Private $name;
Person's name
Private $sex;
The gender of the person
Private $age;
The age of the person
__get () method to get private property
Private Function __get ($property _name) {
if (Isset ($this-> $property _name)) {
Return ($this-> $property _name);
}else{
return (NULL);
}
}
}
The __set () method is used to set private properties
Private Function __set ($property _name, $value) {
$this-> $property _name = $value;
}
__isset () method
Private Function __isset ($NM) {
The echo "Isset () function, when determining private members, automatically invokes <br>";
return Isset ($this-> $nm);
}
__unset () method
Private Function __unset ($NM) {
echo "<br>" automatically invoked when using the unset () function outside the class to delete private members;
unset ($this-> $nm);
}
}
$p 1=new person ();
$p 1->name= "This was a person name";
When you use the Isset () function to determine a private member, the __isset () method is automatically invoked to help us complete, returning the result to True
Echo Var_dump (Isset ($p 1->name)). " <br> ";
echo $p 1->name. " <br> ";
When you delete a private member using the unset () function, the __unset () method is automatically invoked to help us complete, delete the name private property
unset ($p 1->name);
has been deleted, and there is no output for this line.
Echo $p 1->name;
?>

10 clones

Object replication can be done through the Clone keyword (if the __clone () method exists in the object, it is invoked first). The __clone () method in the object cannot be called directly.
When an object is replicated, PHP5 performs a "shallow copy" of all the properties of the object (shallow copy). The references in all properties remain unchanged, pointing to the original variable. If the __clone () method is defined, the __clone () method in the newly created object (the copied generated object) is invoked and can be used to modify the value of the property, if necessary.

I hope this article will help you with the object-oriented programming of PHP.

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.