PHP Object-oriented Essence

Source: Internet
Author: User
Tags vars
1 using extends to implement inheritance and the meaning of overloading, magic methods

Class B extends A

At the time of the Declaration, B could have no way in a.

Called when $b=new B ();

$b method of->a ();

$b the attribute in->a = 1;

$b method of->b ();

$b method of->b ();

If $a=new a ();

OK

$a method of->a ();

$a the attribute in->a = 1;

No

$a method of->b ();

$a method of->b ();

Overloading: B inherits the method property of a, B, and a with the same name.

" overloading " 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 treats all class methods starting with __ (two underscore) as a magic method. So when you define your own class method, do not prefix __.

2 inheritance with private and protected access modifier visibility

Property methods private cannot be inherited

The protected property method is not visible outside the class and can be inherited

The class member defined by the public property method can be accessed from anywhere

3 PHP Double colon:: Application

The PHP class code often sees the "::" operator, which is scoped to the scope operator, and is represented by a double-colon "::", which is used to pin the levels of different scopes in the class. The left side is the member of the access scope to the right of the scope.

The scopes defined in PHP are self and parent two (a 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 also for subclasses to override members and methods in the parent class .

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 ();

Child class overrides parent class

class MyClass
{
protected function myFunc() {
echo "Myclass::myfunc () \ n";
}
}
Class otherclass extends MyClass
{
//Override a method in the parent class
public function myFunc()
{
//But can still call methods that have been overwritten
Parent::myFunc();
echo "Otherclass::myfunc () \ n";
}
}
$class = new Otherclass ();
$class - MyFunc ();

4 This and self and the role of the 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, which does not represent a particular instance of a class, does not work in code other than the 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 a method other than the parent class, but instead extends the overloaded method of the class. Self is a pointer to the class itself, that is, to any object that has already been instantiated, and it is typically used to point to a static variable in the class.

private static $firstCount = 0;
Private $lastCount;
constructor function
function __construct ()
{
$this->lastcount = ++self: $firstCount; Use self to invoke a static variable, using the self call must use::(domain operator symbol)
}

Parent: Represents the scope of the current class parent class, and the rest is the same as the self attribute. Parent is a pointer to the parent class, which we typically use to invoke the parent class's constructor.

Constructors for inheriting classes
function __construct ($personSex, $personAge)
{
Parent::__construct ("test"); The constructor for the parent class was called with parent
$this->personsex = $personSex;
$this->personage = $personAge;
}

5 Constructors and destructors

Classes with constructors Call this method each time an object is created, making it ideal for doing some initialization work before using the object.

function __construct() {}
If a constructor is defined in a subclass, the constructor for its parent class is not implicitly called. To execute the constructor of the parent class, you need to call parent::__construct ()in the constructor of the child class.

PHP 5 introduces the concept of destructors, similar to other object-oriented languages such as C + +. Destructors are removed when all references to an object are deleted or executed when an object is explicitly destroyed.

function __destruct() {}

6 Final keyword

PHP 5 has a new final keyword. If a 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
Has a constructor function No constructors Parent Construct
Has a constructor function Has a constructor function Sub-structure

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 feature of the interface;

3) When implementing multiple interfaces, the methods in the interface cannot have duplicate names ;

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 a quilt class or subinterface.

Declaring 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 an attribute, and a property declaration is made up of the keyword public or protected or private , followed by a variable. A variable in a property can be initialized, but the initialized value must be a constant, where a constant is a constant that the PHP script will be a constant at compile time, rather than the one that was run at runtime after the compilation phase.

In PHP5, two functions "__get ()" and "__set ()" are predefined to obtain
Take and assign its properties, and examine the property's "__isset ()" and the Method "__unset ()" To delete the property.

The simple one is to take the value, and the other is to assign a value. , "__set ()" and "__get ()" Two methods, these two methods are not the default, but we add to the class by hand, like the construction Method (__construct ()), the class is added to exist, you can add these two methods as follows, Of course, it can also be added as a personal style: the//__get () method is used to get the private property

View Plaincopy to Clipboard

  1. class person{
  2. //The following is a member attribute of a person
  3. Private $name; //person's name
  4. Private $sex; //Sex of person
  5. Private $age; //person's age
  6. The //__get () method is used to get the private property
  7. Private function __get ($property _name) {
  8. if (Isset ($this,$property _name)) {
  9. return ($this,$property _name);} Else {
  10. return (NULL);
  11. }
  12. }
  13. }
  14. The //__set () method is used to set the private property
  15. Private function __set ($property _name, $value) {
  16. $this - $property _name = $value ;
  17. }
  18. //__isset () method
  19. Private function __isset ($nm) {
  20. Echo the Isset () function automatically calls when a private member is measured
    ";
  21. return isset ($this,$nm);
  22. }
  23. //__unset () method
  24. Private function __unset ($nm) {
  25. Echo "When you use the unset () function outside of a class to delete a private member, the automatically called
    ";
  26. unset ($this,$nm);
  27. }
  28. }
  29. $p 1 = New Person ();
  30. $p 1 ->name= "This was a person name" ;
  31. //When determining a private member using the Isset () function, the __isset () method is automatically called to help us complete and return the result to True
  32. Echo Var_dump (isset ($p 1->name)). "
    ";
  33. Echo $p 1->name. "
    ";
  34. //When you use the unset () function to delete a private member, the __unset () method is called automatically to help us complete, remove the name private property
  35. unset ($p 1->name);
  36. //has been deleted, there is no output in this line
  37. Echo $p 1->name;
  38. ?>

[PHP] View plaincopy

  1. class person{ ///Below is the member attribute of the person private $name;//person's name private $sex;//person's gender private $age;//person's age//__get () method is used to get the private property Priv Ate function __get ($property _name) {if (Isset ($this-$property _name)) {return ($this-$property _name);} else
  2. { return(NULL);}} The//__set () method is used to set the private property __set ($property _name, $value) {$this, $property _name = $value;}//_ _isset () method The Private function __isset ($nm) {echo ' isset () function automatically calls
    "; Return Isset ($this-$NM); }//__unset () method Private function
  3. __unset ($nm) { echo ] is automatically called when a private member is removed by using the unset () function outside the class.
    "; unset ($this,$nm); }} $p 1=new person (); $p 1 ->name= "This was a person name" ; //When measuring a private member using the Isset () function, the __isset () method is automatically called to help us complete and return the result to true echo var_dump (Isset ($p 1->name)). "
    "; echo $p 1->name. "
    "; When you use the unset () function to delete a private member, the __unset () method is called automatically to help us complete, removing the name private property
  4. unset ($p 1->name); //has been deleted, this line will not have output echo $p 1->name;?>


10 cloning

Object replication can be done by using the Clone keyword (if the __clone () method exists in the object, it is called first). The __clone () method in the object cannot be called directly.

When the object is copied, PHP5 performs a " shallow copy " of all properties of the object (shallow copy). The references in all the attributes remain unchanged , pointing to the original variable. If the __clone () method is defined, the __clone () method in the newly created object (copy generated object) is called and can be used to modify the value of the property, if necessary.

One-to-one PHP references

is to precede variables or functions, objects, etc. with & symbols


The reference in PHP means: Different names access the same variable content.
There is a difference between the pointers in the C language. In the C language, the pointer stores the address of the variable's contents in memory.
a reference to a variable
PHP references allow you to use two variables to point to the same content
[PHP]

$a = "ABC";
$b =& $a;
echo $a;//output here: ABC
echo $b;//output here: ABC
$b = "EFG";
echo $a;//The value of $ A here becomes EFG so the output EFG
echo $b;//output EFG here
?>
[/php]
invocation of a function's address
address Call I'm not going to say much. Directly below the code
[PHP]
function Test (& $a)
{
$a = $a +100;
}
$b =1;
echo $b;//Output 1
test ($b);//Here $b passed to the function is actually the memory address of the $b variable content, by changing the value of $ A in the function can change the value of $b
echo "
";
echo $b;//Output 101
[/php]
It is important to note that here Test (1), the words will be wrong, reason to think
a reference to the function returns
look at the code first
[PHP]
function &test ()
{
Static $b =0;//declaration of a statically variable
$b = $b +1;
echo $b;
return $b;
}
$a =test ();//This statement outputs a value of $b of 1
$a =5;
$a =test ();//This statement outputs a value of $b of 2
$a =&test ();//This statement outputs a value of $b of 3
$a =5;
$a =test ();//This statement outputs a value of $b of 6
[/php]
The following explanation:
In this way $a=test (); The result is not a function reference return, which is not the same as a normal function call. The reason: It's php's rule.
PHP rules by $a=&test (), the way to get the function is a reference to return
As for what is a reference return (the PHP manual says that reference return is used when you want to use a function to find out which variable the reference should be bound to.) I haven't read this bullshit .
in the example above, the explanation is
$a =test () call the function, just assign the value of the function to $ A, and no change to $ A will affect the $b in the function.
by $a=&test (), the function is to call the memory address of the $b variable in the return $b to the same place as the memory address of the $ A variable.
That produces the equivalent effect ($a =&b;) So changing the value of $ A also changes the value of the $b so that it executes the
$a =&test ();
$a =5;
later, the value of the $b becomes 5
This is to let you understand that the function reference returns only use static variables, in fact, the function of the reference return is more used in the object
references to Objects
[PHP]

class a{
var $abc = "abc";
}
$b =new A;
$c = $b;
echo $b->abc;//here output ABC
echo $c->abc;//here output ABC
$b->abc= "DEF";
echo $c->abc;//here output def
?>
[/php]
The above code is the result of running in PHP5
The replication of objects in PHP5 is done by reference. The above $b=new A; $c = $b; is actually equivalent to $b=new A; $c =& $b;
The default in PHP5 is to invoke the object by reference, but sometimes you might want to make a copy of an object, and you want the original object to change without affecting the copy. For this purpose, PHP defines a special method called __clone.
the role of references
if the program is larger, referencing the same object is more variable, and you want to use the object to manually clear it, the personal suggestion to use the "&" method, and then $var=null the way to clear. Other times, it's the default way of PHP5. In addition, in php5 for large arrays, It is recommended to use the "&" method, after all, save memory space.
dereference
when you unset a reference, you just break the binding between the variable name and the variable content. This does not mean that the contents of the variable are destroyed. For example :

$a = 1;
$b =& $a;
unset ($a);
?>
not unset $b, just $a.
Global References
when you declare a variable with the global $var, you actually establish a reference to the global variable. In other words, it is the same as doing this:

$var =& $GLOBALS ["var"];
?>
This means, for example, that the unset $var does not unset global variables.
$this
In the method of an object, $this is always a reference to the object that called it.
Here's a little episode.
PHP in the direction of the address (similar to the pointer) function is not implemented by the user itself, is implemented by the Zend Core, PHP refers to the use of "copy-on-write" principle, that is, unless a write operation, the same address to the variable or object is not copied.
The popular Speaking
1: If you have the following code
[PHP]
$a = "ABC";
$b = $a;
[/php]
In fact, $a and $b both point to the same memory address and not $ A and $b occupy different memory
2: If you add the following code based on the above code
[PHP]
$a = "EFG";
[/php]
since $ A and $b point to the memory of the data to be re-written once, at this time Zend core will automatically decide to automatically produce a $ A copy of the data for $b, re-request a piece of memory for storage

The above describes the PHP object-oriented essence, including the aspects of the content, I hope that the PHP tutorial interested in a friend helpful.

  • Related Article

    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.