The usage of PHP class class detailed summary _php skill

Source: Internet
Author: User
Tags autoload class manager inheritance php class reflection getv

One: Structure and invocation (instantiation):

Class classname{}, calling: $obj = new ClassName (), and when the class has a constructor, it should also pass in the argument. such as $obj = new ClassName ($v, $v 2 ...);

Two: Constructors and destructors:

1. Constructors for initialization: using __construct (), with parameters.

2, but destructors cannot take parameters (used to perform some operations or functions before a class is sold). The destructor is named with __destruct (). At the end of the script execution, the object in memory is sold out, so you do not have to make a destructor, but some, such as cookies, should be sold out with this function.

Knowledge Points: Constructors are also provided in PHP4, but using class methods with the same name as the class, which can still be compatible with PHP5, when a class does not contain __construct, it looks for a method with the same name as the class, which, if found, is considered a constructor, as follows:

Copy Code code as follows:

Class Test
{var $b;
function test () {$this->b=5;}
function Addab ($c) {return $this->b+ $c;}
$a = new test (); Echo $a->addab (4); Return 9

3. PHP does not automatically invoke the constructor of the parent class (constructors overload is not supported) and must be explicitly invoked using the parent keyword.
Copy Code code as follows:

Class employee{
function __construct () ....
Class Manager Extents employee{
function __construct () {
Parent::_construct ();
Echo ' The parent class constructor of this subclass is called! ';

Of course, you can also invoke constructors for other classes that have no relationship to the instance. Just precede the __construct () with the class name. Such as:
Otherclassname::__construct ();

Main family members of a class: properties, methods, constants, static members

Third, the properties of the class:
There are two ways to assign or take a value on a class's properties.
1. Use public domain keywords.
2, using __set () and __get () to assign values and values respectively, the former is called Set method (setter) or modify method (Mutator), the latter is called access method (accessor) or Get method (getter). This approach is recommended: advantages:
A, can be in __set () unified data validation.
B, easy to unify management attributes.


First: __set () and __get () only work on private properties, and two of them are lazy for properties defined with public, as follows:

Copy Code code as follows:

Class test{
Protected $a =9, $b =2, $c;
Public $d;
function __set ($n, $v) {$this-> $n = $v +2;}
function __get ($name) {return $this-> $name +2;}
$a = new test ();
$a->b = 5; echo "<br/>"; Echo $a->b;

Instances are only for $a, $b, $c settings are filtered and returned by __set and __get, and for $d, it will not work. such as $a->d=5, return or 5.

Second: __set ($n, $v) to take two parameters. __get ($n) can have only one parameter. Instance:

Copy Code code as follows:

Class test{
Private $a =5, $b =6, $c;
function __set ($n, $v)
if ($n = = ' A ' && $n >0)
$this-> $n = $v;
$this-> $n = $v +2;
function __get ($name)
return $this-> $name; If you change to return $this-> $name + $this->addab (); If you call the value of a, the value of A+a+b is actually returned. Default is 5+5+6=16.
function Addab ()
{return $this->a + $this->b;}
$e =new test ();
$e->a = 11; Note: The internal use of $this-> $n that is the variable, but the external instance to use the $e->a way.
$e->b = 12; Get 14
$e->k = 22;

The properties of a class can be expanded freely, as in the case of the above example K, whether or not using __set, when an instance is established, you can use $e->newproperty = XX to create a property directly, but not recommended.

Four, the class method:
Understand the functions in a class.


1, internal call: can use $this->fanname (); or $this->addab () or Test::addab ();

2. When the call is instantiated, use $e->addab (); For those that do not use the $this keyword in this method, as in the previous example:
function Addab () {return $this->a+ $this->b;}
Change to: Function Addab () {return 25;} The method is invoked in an external instance, and is also available as "$e:: Addab ();" or "Test::addab ();"

The constants of the class:
If the properties of a class are understood as variables in a class, the constants and variables of the class are not the same, and the method is defined as:

Copy Code code as follows:

Class test{
Private $a;
Const PI = ' 3.14′;
There are two ways to call the constants above in a class, "$this::P i", or "class name::P I", this is test::P I, as follows:
function GetValue () {
return $this->a * $this::P i; or $this->a * Test::P I, with the This keyword or class name, but with a double colon.
$e = new test ();
$e->pi = 5; Note that using-> only creates a property that is also named Pi, rather than changing the value of the PI constant in the class.
echo $e::P i; This is the constant that invokes the class.

Constants can only be invoked with a double colon::. and cannot change its value.
There are also two ways to invoke a class constant after instantiating it outside of a class. The method is:
"$e::P i" or "Test::P i", the common point is to use a colon, the difference is that the external cannot use the This keyword, only the instance name, but the class name::P i is generic.

Static member of Class (static property or static method):

If you need to create fields or methods that are shared by instances of all classes. You have to use static members. There are two characteristics:

1, the static member is a communist, it lets all instances of the class on the script invoke, but not by the class of a specific instance name invoked, but outside the class, unified use of "class name:: $ member name" method call. The internal of the class is called using the "self::$ member name" uniformly.

2. When each new instance is created, the static member begins the recalculation from the last value of the last created instance, rather than starting with the initial value in the class.

3. For static members defined with public, you can change the value of it externally. Private and so on is not good.

Copy Code code as follows:

Class test{
public static $v = 0;
function __construct () {self:: $v + +;}
static function Getv () {return self:: $v;}
$a = new test ();
Echo Test::getv (); Return 1
$b = new test ();
Echo Test::getv (); Return 2
Test:: $v = 8; Changes the value of a static member because of a member of the public definition.
$c = new test ();
Echo Test::getv (); Return 9

Seven, the key word:
(i) This keyword: the internal reference class for the class itself. To access a property or method or constant, such as a $this-> property name or a method name. $this:: Constant name. This can also be used in subclasses of the class to refer to a property or method of its own.

(ii) Double colon "::" Keyword: used to invoke constants, static members.

(iii) SELF keyword: a static member is called in conjunction with a double colon within a class, such as self:: $staticVar., within a class, static members cannot be invoked with $this.

(iv) __tostring (): Use __tostring () in a class to convert a class to a string and print a class for a small purpose: for example:

Copy Code code as follows:

Class test{public $p;
Public Function __tostring () {return Var_export ($this, TRUE);}
$a =new test ();
echo $a; Output: Test::__set_state (Array (' P ' => NULL,), or written as: Echo $a->__tostring ();

(v) __clone (): When cloning an object, this keyword is used to change certain values when cloning.

(vi) __call (): Method overload, the following example:

Copy Code code as follows:

Class cb{
function __call ($method, $n) {
if ($method = = ' Showvartype ') {
if (is_numeric ($n [0])) {//$n cannot be used. To use $n[0];
$this->displaynum ();
}else if (Is_array ($n [0])) {
$this->displayarr ();
$this->displayother ();
function Displaynum () {
Echo ' }
function Displayarr () {
Echo ' }
function Displayother () {
Echo ' }

$x = ' a ';
$y =array (' A ', ' B ');
$b =new CB;
$b->showvartype ($x); Not an array, not a number.
$b->showvartype ($y); This is an array

Note that the Showvartype () method cannot be defined in the class, otherwise the code will not work.

(vii) extends: inheritance: such as Class a{} Class B extends a{} Class B inherits Class A

Attachment: Memory: Future unification with "->" when calling a method or property, a constant is invoked with a double colon "::", not dizzy.

Viii. scope of methods and properties:

A total of 6 kinds: public (default, can be omitted, also equivalent to the PHP6 var declaration), Private (private, also can not be used by subclasses), protected (private, but can be used by subclasses), abstract (abstract, context), final (block in the subclass to prevent overwriting- Also known as overloading, block is inherited, used to modify class names and methods, such as final class test{final function fun () {}}, but not for attributes), static (static)

IX: Abstract classes and abstract methods (abstract--Note: There is no abstract attribute):

An abstraction can be understood as a parent class that defines a template or base class for a subclass. Scope Abstract is declared only in the parent class, but is implemented in subclasses. Precautions:

1, abstract class can not be instantiated, can only quilt class (concrete Class) After the implementation of inheritance.

2. An abstract class must implement all the abstract methods of the abstract class in its subclasses. Otherwise there will be an error.

3, in the abstract method, just declare, but can not be implemented concretely: such as abstract function Gettow () {return $this->p;} Is wrong, you can only declare this method: Abstract function Gettow () (not even brackets {}), abstract methods and abstract classes are mainly used in complex class-level relationships. This hierarchical relationship needs to ensure that each subclass contains and overloads some specific methods. This can also be achieved through the interface

4, the attribute cannot be named abstract property, such as abstract $p = 5 is wrong.

5. Only classes declared as abstract can declare abstract methods, but they cannot be implemented if the method is declared abstract. Such as:

Copy Code code as follows:

Abstract class Employee
Abstract function A (...);
Abstract function B (...);

Later, the parent class is extended to form a variety of subclasses such as managers, employees, and cashiers.

6, in the abstract class, if you want to implement a specific method, cannot be declared as abstract. That might actually be more meaningful. You can extract the common parts of several class libraries into an abstract class, and the other classes inherit the abstract class. As follows:

Copy Code code as follows:

Abstract class baseshop{
Const tax=0.06; Defining constants in an abstract class
Public function Buy ($gid) {//If defined as an abstract method, the abstract function buy () cannot implement the body here.
Echo (' you purchased the product with ID: '. $gid. ');
Public function Sell ($gid) {
Echo (' You sold the product with ID: '. $gid. ');
Public Function View ($gid) {
Echo (' You look at the product with ID: '. $gid. ');
Class Ballshop extends baseshop{
var $itme _id = null;
Public Function __construct ()
$this->itme_id = 2314;
Public Function open ()
$this->sell ($this->itme_id);
Public Function Gettax ()
echo printf (' }
$s = new Ballshop;
$s->open (); You sold a product with ID: 2314
$shop->gettax ();

10: Type hint:
Note that the type hint feature can only be used for hints that have parameters as objects, not for types such as integers, strings, floating-point, and so on. Some classes have methods that require incoming parameters to be the desired object type, and you can use the following method to enforce the workaround. To achieve a type hint, simply add the name of an existing class to the object type parameter of the method, such as function Funname (Otherclassname $otherclassINSName, $c ...), note that Otherclassname must be a class that exists. As follows:
Copy Code code as follows:

Class em{var $k = 56;}
Class test{
function __construct ()
{echo $this->addab (New Em (), 2);}

function Addab (em $j, $c)//This method, which can be called internally or externally. As long as the scope is licensed.
{return $j->k+ $c;}
$a = new test ();
$b = new Em ();
echo $a->addab ($b, 2); or $a->addab (new Em (), 2);

11, the management of the class:

1. Instanceof keywords: Used to analyze whether an object is an instance or subclass of a class or implement a particular interface: The following example, but note that the class name does not have any quotes and other delimiters, otherwise there will be an error. If test cannot use ' test '

Copy Code code as follows:

Class test2{}
Class test{}
Class Testchilern Extends test{}
$a = new Test2 ();
$m = new test ();
$i = ($m instanceof test);
The IF ($i) echo ' $m is an instance of class test! <br/> '; Get this value
Switch ($a instanceof test) {
Case true:
echo ' yes<br/> ';
Case false:
echo ' no<br/> '; Get this value
$d =new Testchilern ();
if ($d instanceof test) echo ' $d is a subclass of class test! <br/> '; Get this value

2, determine whether the class exists: Boolean class_exists (String class_name): class_exists (' Test ');

3. Returns the class name: String Get_class (Object), returns the class name of the instance when it succeeds, and returns False if it fails:

$a = new Test2 (); echo Get_class ($a); Back to Test2

4, understand the common properties of the class: Array get_class_vars (' ClassName '), return a critical array: Contains all the definitions of the public property name and its corresponding value. This function cannot be used as a variable with the instance name

5, the Return class method: Get_class_methods (' Test '); Or: Get_class_methods ($a), using the instance name as a parameter, and returning all non-public methods, including constructors.

6, Print_r (Get_declared_classes ()) to understand the current PHP version of the class name. There are 149 PHP5.

7, Get_object_vars ($a) returns an associative array of all common properties and their values in the instance. Notice the difference between it and Get_class_vars ():
/* (1) get_object_vars ($a) is a parameter with the instance name, and Get_class_vars (' test ') is a parameter with the class name.
* (2) The property value obtained by Get_object_vars ($a) is the value after the instance is run, and the property value obtained by Get_class_vars (' test ') is the initial definition in the class.
* (3) Both return an associative array, and all return null values for unassigned properties. If there is a public $q defined in class test, the array ([v] => 5 [q]=>) is returned.

8, return the name of the parent class: Get_parent_class ($b);///Get_parent_class (' test2′); Return to test

9, determine whether the interface exists: Boolean interface_exists ($string interface[,boolean autoload])

10. Determines the object type: Boolean is_a ($obj, ' className '), returns True when $obj belongs to the ClassName class, or belongs to its subclass, and returns False if $obj is independent of class type. such as: is_a ($a, ' test ')

11, determine whether it is a class of child objects: When $b is inherited from the test class, return True, otherwise false. Boolean is_subclass_of ($b, ' test ');

12. To determine whether a method exists in a class or instance. Method_exists ($a, ' getv ')//or with method_exists (' Test ', ' Getv '), this function applies to methods that are not public-defined scopes.

Above examples of functions:

Copy Code code as follows:

Class test{
Public $v = 2;
Private $c = 5;
function __construct () {
Private Function Getv () {
return $this->v;
Class Test2 extends test{}

$a =new test ();
$b =new test2 ();
Print_r (get_class_methods (' Test ')); Or: Print_r (get_class_methods ($a)); All returns: Array ([0] => __construct [1] => Getv)
echo ' <br/> ';
Print_r (get_class_vars (' Test ')); Returns: Array ([v] => 2), unlike the above, cannot be Print_r (Get_class_methods ($a));
echo ' <br/> ';
echo Get_parent_class ($b);//or Get_parent_class (' test2′); Return to test
echo ' <br/> ';
Echo is_a ($b, ' test ');//return 1
echo ' <br/> ';
if (is_subclass_of (' test2′, ' Test ')) Echo ' is a subclass! '; or (Is_subclass_of ($b, ' test '), returns 1, returns false when parameter 1 is $a,
echo ' <br/> ';
Echo method_exists ($a, ' getv ')//or returns 1 with method_exists (' Test ', ' Getv '), which also applies to methods that define fields with private.

11. Automatically load class library file:

When more than one class, for example, to load 3 class library files in a file: a.class.php,b.class.php,c.class.php to use three require_once (' classes/a.class.php);

Require_once (' classes/b.class.php);
Require_once (' classes/c.class.php);

PHP5 can be handled automatically by using the function of automatic loading: In the Global application configuration file, define a special function __autoload ($class) function (__autoload is not a method of a class, just a separate function, and the class has no relationship):
function __autoload ($class) {
Require_once ("classes/$class)

It doesn't matter where the function is, and you don't have to call the AutoLoad function when you create the class instance. PHP will be done automatically. However, it is important to note that "the class name used to create the instance on the calling page", and "filename of the call", and "the name of the class in the file" 3 must be the same. This means that you do not need to invoke __autoload (), and if not, you must call __autoload (' C ') separately, and give it a filename prefix. Such as:
The code for the c.class.php file is:

Copy Code code as follows:

Class c{
Public $m = 7;

The class name of the code here is C, and the filename is C,
Now you want to call in index.php:
Copy Code code as follows:

function __autoload ($class) {
Require_once "$class. class.php";

$m = new C (); The class that creates the instance call is also C
Echo $m->m;

At this point, PHP will automatically call Class C in the c.class.php in the root directory.

But if the code in c.class.php is:

Copy Code code as follows:

Class mm{
Public $m = 7;

and the calling page index.php code is:
Copy Code code as follows:

function __autoload ($class) {
Require_once "$class. class.php";
# __autoload (' C '); If you do not add this line, you will get an error.
$m = new mm ();
Echo $m->m;

There will be an error, prompting that the mm.class.php file cannot be found. You can add a line of __autoload (' C '), but that's not the way to simplify your code.

Family extensions of classes: Advanced Features of classes:

One, object cloning:
When an instance of an object is cloned, its property initial value inherits the current value of the cloned object.

Copy Code code as follows:

Class Test
Public $p = 5;
function __clone () {//only works when cloning occurs. Used to change some values at the time of cloning
$a =new test ();
Echo $a->p;
$a->p=8; If no __clone () method affects, the P value of the $b will be 8
$b = Clone $a;
Echo $b->p; 15

second, object inheritance:

Classes that are not declared final can be inherited, and methods that are not defined by final and private can also be inherited, and attributes that are not defined by private can also be inherited. When a subclass inherits a parent or superclass, you can directly use all of the allowed methods, attributes, of the parent or superclass (grandparent and grandparent).
Key: Understand the attributes of constructors and overloads in inheritance!

(i) Attributes of the constructor in inheritance:

1, when the parent class has constructors and subclasses do not: Then the subclass will automatically execute the constructor of the parent class when instantiated. In this case, if you want to create an instance of a subclass, you need to introduce the parameters that are required in the parent class constructor, otherwise an error occurs. Even if a subclass of subclasses does not have a constructor, you also enter the parameters required for the constructor of the parent class of the parent class when the instance is created. PHP searches up the constructed constructor from the subclass where the instance is located, and stops when it is found, using the constructor. Instead of searching up again, the subclass itself, if it does not have a constructor, takes its closest superclass and has the constructor as the class.

Copy Code code as follows:

Class ca{
Public $name, $age;
function __construct ($n) {
$this->name = $n;
$this->age = 25;
function __set ($n, $v) {
$this-> $n = $v;
function __get ($n) {
return $this-> $n;

Class CB extends ca{
function funB1 () {echo ' }

Class CC extends CB {
function funC1 () {echo ' }
$b =new CB (' Jack ');
$b->name= ' John ';
echo "$b->name: $b->age";
$b->funb1 ();
$c =new CC (); There will be errors, because CB also does not have a constructor, so go up to the CA as the standard, need a parameter. Change to $c=new CC (' David ');
echo $c->name (); David

2, when the subclass also has a constructor: at this point, regardless of whether the parent class has a constructor, it executes the subclass's own constructor.
Copy Code code as follows:

Class CB extends ca{
function __construct () {
Echo ' }
function funB1 () {
Echo ' }

Now the class CB has its own constructor, then the instance $b=new CB (' Jack ') is created; parameter Jack does not work because the parent class CA's constructor is not executed. Therefore, $b->name and $->age do not initialize the values. Need additional assignment $b->name= ' Jack ', $b->age=25;
If you want to execute the constructor of the parent class CA at this point, you can do this:
Copy Code code as follows:

function __construct ($n) {
Parent::__construct ($n); Or: Ca::__construct ($n);
Echo ' }

Due to parent::__construct ($n); Only the constructor of the parent class is searched up, and the currently found constructor is stopped and executed as soon as it is found, so in the example above, if Parent::__construct ($n) is used in the last layer of class CC, and the class Cb,ca has constructors, Then the instance of CC will only execute the CB constructor. CA will not be executed. At this point, if the instance of CC wants to call the CA and CB constructors, there are two ways:

A, in the CB also joined Parent::__construct ($n)
B, in CC, change the constructor to:

Copy Code code as follows:

function __construct ($n) {
Ca::__construct ($n); That is: Class Name:: Constructor.
Cb::__construct ();
Echo ' }

(ii) Invoke the properties or methods of the parent class in subclasses:

1. Call the parent class method: There are 3 ways to invoke the parent class in a subclass:
$this->parentfunction (); Or
Parent class Name::P arentfunction (); Or
Parent::p Arentfun ();

2, invoke the parent class property: can only use $this->parentproperty;

(iii) Overloading:

In a subclass, you can define the same property or method as the parent class, changing the value or operation of the property or method of the parent class, which is called overloading. Such as:
CALSS parclass{function Pfun () {...}}
Class Childrenclass extends Parclass{function Pfun () {...}}}//Overloaded the Pfun method of the parent class.
After overloading in a subclass, a newly defined method or property that takes precedence over its own overload is executed.
You can also use parent::p Arentfun () in subclasses, calling methods of the parent class, but the resulting value is the parameter operation value entered by the subclass itself. Rather than the value of the method's operation in the parent class.

Third, Interface:

Interface: interface, which can be understood as a common specification of a set of functions, the greatest meaning may be in the collaboration of many people, for their own development to specify a common method name.

As with abstract methods in abstract classes:

1, can not be defined in the interface of the implementation of the method. Rather, it is implemented by specific classes (while Non-abstract methods in abstract classes can no longer be defined, and only abstract methods and interfaces are required to be implemented in a specific class).

2, as with abstract classes, you can define constants in an interface and inherit directly from a specific class.

3. The concrete class must implement all abstract methods of the abstract class (except for Non-abstract methods), as well as the concrete class, which implements the interface through implements, must complete all the methods in the interface.

Interface implementation process: 1, define interface, 2, with ... Implement X,y,... and concrete class docking.

Copy Code code as follows:

interface info{//definition interface
Const N=22;
Public function getage ();
Public function getname ();

Class Age implements Info//If you want multiple interfaces class age (extends Emjob) implements Info,interb ...
Public $age = 15;
Public $name = ' Join ';
function Getage () {
echo "Grade is $this->age";
function GetName () {
echo "name is $this->name";
function Getn () {
Echo ' }

$age =new age;
echo $age:: N; 22, call the constant value in the interface directly.
$age->getn ();

About the use of abstract classes and interface classes: When to use interfaces, when to use abstractions?

1, relevance: When the model created by a number of closely related objects adopted, with the abstract. For unrelated objects, use the function of the interface.

2, multiple Inheritance: PHP classes can inherit multiple interfaces, but cannot extend multiple abstract classes.

3, public behavior implementation: Abstract classes can be implemented in which the public method, but the interface is not.

Four, the name Space (PHP6)

Class Library script and script all have the name of Class CNAME, and the two files are called in the same file as index.php. You need to use a namespace.

Step Poly:

1, open the above A and B two files, respectively, in the top of the above each add a line:

namespace Spacea; and namespace Spaceb; The name is a self definite.

2. When instantiating a class in index.php, add the namespace and double colon as prefixes before the class:
Include ' ';
Include ' ';
$a =new spacea::cname ();
$b =new spaceb::cname ();

So there's no conflict.
But before the official release of PHP6, this function was still undecided.

Implement Iterators and Iterations.
"PHP Bible" P142;

Vi. Use the Reflection (reflection) API.
Simple example:
Class a{...}
$c = new Reflectionclass (' a '); PHP built-in classes.
Echo ' <pre> '. $c. ' </pre> ';
Outputs the structure and content of Class A. "PHP Bible" P145;

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: 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.