A detailed summary of PHP class usage

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

The following is a detailed summary of the use of class in PHP, the need for friends can come to the reference

One: Structure and invocation (instantiation):

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

Two: Constructors and destructors:

1. Constructors are used for initialization: Use __construct (), with parameters.

2, but the destructor cannot take parameters (used to perform some operations or functions before the pin goes to a class). Destructors are named with __destruct (). At the end of the execution of the script, the objects in memory are sold out, so there is no need to analyze the functions, but some, such as cookies, should be sold off with this function.

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

Copy CodeThe code is 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); Returns 9
3. PHP does not automatically call the parent class's constructor (which does not support constructor overloading) and must be explicitly called using the parent keyword.
Copy CodeThe code is as follows:
Class employee{
function __construct () ....
}
Class Manager Extents employee{
function __construct () {
Parent::_construct ();
Echo ' The parent constructor of this subclass is called! ‘;
}
}
Of course, you can also call the constructors of other classes that do not have any relation 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

The properties of the class:
There are two ways to assign or value the properties of a class.
1. Use public scopes to common keywords.
2, using __set () and __get () to assign values and values, the former is called the Set method (setter) or modify method (Mutator), the latter is called the Access method (accessor) or Get method (getter). It is recommended to use this method: advantages:
A, data validation can be performed uniformly in __set ().
B, to facilitate the unified management of properties.

Attention:

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

Copy CodeThe code is 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;
The instance is 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) takes two parameters. __get ($n) can have only one parameter. Instance:

Copy CodeThe code is as follows:
Class test{
Private $a =5, $b =6, $c;
function __set ($n, $v)
{
if ($n = = ' A ' && $n >0)
$this $n = $v;
Else
$this $n = $v +2;
}
function __get ($name)
{
return $this $name; If you change to return $this $name + $this->addab (); If the value of a is called, the value of A+a+b is actually returned. The default is 5+5+6=16.
}
function Addab ()
{return $this->a + $this->b;}
}
$e =new test ();
$e->a = 11; Note: The internal use of the class $this-> $n that is, the variable, but the external instance to use $e->a way.
$e->b = 12; Get 14
$e->k = 22;
The properties of the class can be freely extended, as in the above example K, whether or not with __set, when an instance is established, you can use $e->newproperty = XX; directly to create a property, but it is not recommended.

Iv. methods of the class:
Understand the functions in a class.

Call:

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

2. When instantiating the call, use $e->addab (); For the $this keyword is not used in this method, as in the previous example:
function Addab () {return $this->a+ $this->b;}
Instead: function Addab () {return 25;} That method is called in the external instance, also available "$e:: Addab ();" or "Test::addab ();"

Constants of Class V:
If the properties of a class are understood as variables in a class, then the constants and variables of the class are different and are defined by:

Copy CodeThe code is as follows:
Class test{
Private $a;
Const PI = ' 3.14′;
.....
Call the above constants in a class in two ways, "$this::P i", or "class name::P I", here is test::P I, as follows:
function GetValue () {
return $this->a * $this::P i; or $this->a * Test::P I, use the This keyword or class name, but both use a double colon.
}
}
$e = new test ();
$e->pi = 5; Note that here, just create a property called Pi, instead of 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 double colons::. And you cannot change its value.
Calling a class constant after an outside instantiation of a class also has two methods. The method is:
"$e::P i" or "Test::P I", in common is to use a colon, the difference is that the external cannot use the This keyword, only with the instance name, but the class name::P i is generic.

Vi. static members of a class (static properties or Static methods):

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

1, a static member is a communist, it makes all instances of the class on the script call, but not with the use of the class's specific instance name, but outside of the class, unified use "Class Name:: $ member name" method called. The inside of the class is invoked uniformly using the "self::$ member name".

2. When a new instance is created each time, the static member is recalculated from the last value of the last instance created, not the initial value in the class.

3. For a static member defined with public, you can change its value externally. Private and so on are not.

Copy CodeThe code is as follows:
Class test{
public static $v = 0;
function __construct () {self:: $v + +;}
static function Getv () {return self:: $v;}
}
$a = new test ();
Echo Test::getv (); Returns 1
$b = new test ();
Echo Test::getv (); Returns 2
Test:: $v = 8; The value of the static member is changed because of the member defined by public.
$c = new test ();
Echo Test::getv (); Returns 9
Seven, the key words:
(i) this keyword: used for the internal reference class of the class itself. To access a property or method or constant, such as a $this-> property name or 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.

(c) The Self keyword: calls a static member inside a class with a double colon mate, such as self:: $staticVar. Inside a class, you cannot invoke a static member with $this.

(iv) __tostring (): Use __tostring () in a class to turn the class into a string and print the class, which is of little use: for example:

Copy CodeThe code is 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 (): This keyword does not function when cloning an object, and is used to change certain values when cloning.

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

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

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


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

(vii) Extends: Inheritance: Class a{} Class B extends a{} classes B inherits classes a

Attached: Memory: Later unified in the call method or property with "," and call the constant with a double colon "::", will not be confused.

Viii. scope of methods and properties:

There are 6 kinds: public (default, can be omitted, also equivalent to PHP6 var declaration), Private (private, also cannot be used by subclasses), protected (private, but can be used by subclasses), abstract (abstract, reference), final (block in subclasses- Also known as overloading, block inherited, used to decorate class names and methods, such as final class test{final function fun () {}}, but not for properties), static (static)

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

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, only quilt class (concrete Class) After the implementation of the 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 specifically implemented: such as abstract function Gettow () {return $this->p;} Is wrong, can only declare this method: Abstract function Gettow (); (not even square brackets {}), abstract methods and abstract classes are mainly used in complex class hierarchy 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. Attribute cannot be named abstract attribute, such as abstract $p = 5 is wrong.

5. Only a class that is declared abstract can declare an abstract method, but if the method is declared abstract, it cannot be implemented specifically. Such as:

Copy CodeThe code is as follows:
Abstract class Employee
{
Abstract function A (...);
Abstract function B (...);
}
Later on, the parent class is extended to form various subclasses (such as managers, employees, cashiers).

6. In an abstract class, if you want to implement a specific method, you cannot declare it abstract. This may actually be more meaningful. You can extract the common parts of several class libraries into an abstract class, and other classes inherit the abstract class. As follows:

Copy CodeThe code is as follows:
Abstract class baseshop{
Const tax=0.06; Defining constants in abstract classes
Public function Buy ($gid) {//If it is defined as an abstract method, abstract function buy () cannot implement the principal here.
Echo (' You have purchased ID: '. $gid. ' Goods ');
}
Public function Sell ($gid) {
Echo (' You sold the ID for: '. $gid. ' Goods ');
}
Public Function View ($gid) {
Echo (' You've looked at the ID: '. $gid. ' Goods ');
}
}
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 an ID of: 2314
$shop->gettax ();
10: Type tip:
Note that the type hint feature can only be used for hints that are arguments to objects, but not for types such as integers, strings, floating-point, and so on. Some methods of a class require that the passed parameter be the desired object type, which can be enforced by the following method. To reach a type hint, simply add the name of an existing class before 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 CodeThe code is 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, can also be called 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 keyword: Used to analyze whether an object is an instance or subclass of a class or implement a specific interface: The following example, but note: The class name does not have any delimiters such as quotation marks, otherwise it will be an error. If test cannot use ' test '

Copy CodeThe code is 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/> ';
Break
Case false:
echo ' no<br/> '; Get this value
Break
}
$d =new Testchilern ();
if ($d instanceof test) echo ' $d is a subclass of class test! <br/> '; Get this value
2. Determine if 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 on success, and 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 '), which returns the key array: contains all the defined public property names and their corresponding values. This function cannot be used as a variable with instance name.

5, Return class method: Get_class_methods (' Test '); Or: Get_class_methods ($a); Use the instance name to make parameters that return all non-private methods including constructors.

6, Print_r (get_declared_classes ()) know all the class names in the current PHP version. There are 149 of PHP5.

7, Get_object_vars ($a) returns an associative array of all the common properties and their values in the instance. Notice the difference between it and Get_class_vars ():
/* (1) get_object_vars ($a) is the argument with the instance name, and Get_class_vars (' test ') is the 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 associative arrays, and both return null values for unassigned properties. If the public $q is defined in class test, the array ([v] = 5 [q]=>) is returned,
*/

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

9. Determine if the interface exists: Boolean interface_exists ($string interface[,boolean autoload])

10. Determine the object type: Boolean is_a ($obj, ' className '), returns True if $obj belongs to the ClassName class, or its subclasses, or False if $obj is not related to class type. such as: is_a ($a, ' test ')

11. Determine if it is a child of a class: Returns True if $b is inherited from the test class, otherwise false. Boolean is_subclass_of ($b, ' test ');

12. Determine if there is a method in the class or instance. Method_exists ($a, ' getv ')//or with method_exists (' Test ', ' Getv '), this function applies to non-public defined scope methods.

Example of the above function:

Copy CodeThe code is as follows:
Class test{
Public $v = 2;
Private $c = 5;
function __construct () {
$this->v=5;
}
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 return: Array ([0] = __construct [1] = Getv)
echo ' <br/> ';
Print_r (get_class_vars (' Test ')); return: Array ([v] + 2), not the same as above, can not be used 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, false when argument 1 is $ A,
echo ' <br/> ';
Echo method_exists ($a, ' getv ')//or return 1 with method_exists (' Test ', ' Getv '), this function also applies to the method of defining the domain with private.


11. Automatic loading of Class library files:

When the class is more, for example, in a file to load 3 class library files: 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);

Can be handled with PHP5 Auto-load: 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, not related to a class):
function __autoload ($class) {
Require_once ("classes/$class)
}

It doesn't matter where the function is, nor does it have to call this autoload function when creating an instance of the class. PHP is automatically completed. However, it is important to note that "the class name used to create the instance on the invocation page", and "called File name", and "the name of the class in the file" 3 must be the same. This does not need to call __autoload (); 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 CodeThe code is as follows:
< PHP
Class c{
Public $m = 7;
}
?>
The class name of the code here is C, and the file name is C,
Now to invoke in index.php:
Copy CodeThe code is as follows:
< PHP
function __autoload ($class) {
Require_once "$class. class.php";
}

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


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

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

Copy CodeThe code is as follows:
< PHP
Class mm{
Public $m = 7;
}
?>
The calling page index.php code is:
Copy CodeThe code is as follows:
< PHP
function __autoload ($class) {
Require_once "$class. class.php";
}
# __autoload (' C '); If you don't add this line, you'll get an error.
$m = new mm ();
Echo $m->m;
?>
An error occurred indicating that the mm.class.php file could not be found. You can add a line of __autoload (' C ') at this point, but this will not achieve the purpose of simplifying the code.

Family extensions for classes: Advanced features of classes:

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

Copy CodeThe code is as follows:
Class Test
{
Public $p = 5;
function __clone () {//only works when a clone occurs. Used to change certain values at the time of cloning
$this->p=15;
}
}
$a =new test ();
Echo $a->p;
$a->p=8; If no __clone () method is affected, the $b p-value 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 are inherited, and properties that are not defined by private can also be inherited. When a subclass inherits from a parent class or superclass, you can directly use all the allowed methods, attributes of the parent class or superclass (Grandfather class and grandfather's grandfather).
Key: Understand the properties of constructors and overloads in inheritance!

(a) The characteristics of the constructor in inheritance:

1. When the parent class has a constructor and the subclass does not: The subclass will automatically execute the constructor of the parent class when it is instantiated. If you want to create an instance of a subclass, you need to introduce the parameters required in the parent class constructor, or else an error occurs. Even if the subclass of the subclass does not have a constructor, you also enter the parameters required by the constructor of the parent class of the parent class when you create the instance. PHP will search up the constructed constructor from the subclass of the instance, and stop if found, using the constructor. Instead of searching upwards, the subclass itself, if there is no constructor, is the one that is closest to the superclass and has a constructor.

Copy CodeThe code is 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 an error here, because CB also has no constructor, so the upward to the CA, the need for 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, the subclass's own constructor will be executed.
Above
Copy CodeThe code is as follows:
Class CB extends ca{
function __construct () {
Echo ' }
function funB1 () {
Echo ' }
}
Now that the class CB has its own constructor, the instance $b=new CB (' Jack ') is created, and the parameter Jack does not work because the constructor of the parent class CA is not being executed. Therefore, $b->name and $->age do not initialize the values. Additional assignment is required $b->name= ' Jack ', $b->age=25;
If you want to execute the constructor of the parent class CA at this point, you can:
Copy CodeThe code is 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 constructor that is currently found 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. The CA is not executed. At this point, if the instance of CC wants to call the CA and CB constructors, there are two methods:

A, in the CB also joined Parent::__construct ($n)
B. In cc, change the constructor function to:

Copy CodeThe code is as follows:
function __construct ($n) {
Ca::__construct ($n); That is: Class Name:: Constructor.
Cb::__construct ();
Echo ' }
(ii) Call the property or method of the parent class in the subclass:

1. Call the parent class method: The method of calling the parent class in the subclass, there are 3 methods:
$this->parentfunction (); Or
Parent class Name::P arentfunction (); Or
Parent::p Arentfun ();

2. Call the parent class property: only with $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 parent class's property or method, called overloading. Such as:
CALSS parclass{function Pfun () {...}}
Class Childrenclass extends Parclass{function Pfun () {...}}}//Overloads the Pfun method of the parent class.
After overloading in a subclass, the new defined method or property is executed with precedence over the overloaded one.
You can also have the parent::p Arentfun () in the subclass, call the method of the parental class, but the resulting value is the parameter operation value that the subclass has entered for itself. Instead of the value that the method is operating in the parent class.

Third, the interface:

Interface: interface, can be understood as a set of functions of the common norms, the greatest significance may be in the multi-person collaboration, for their own development to provide a common method name.

Is the same as an abstract method in an abstract class:

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

2. As with abstract classes, constants can be defined in interfaces and inherited directly from specific classes.

3, the concrete class must implement all abstract methods of the abstract class (except for non-abstract methods), similarly, the concrete class, such as the implementation of the interface through implements, must complete all the methods in the interface.

Interface implementation process: 1, define the interface, 2, with. Implement X, Y,... and specific class docking.

Copy CodeThe code is as follows:
Interface info{//define 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 an interface, when to use abstraction?

1, relevance: When the model is created by some closely related objects adopted, with abstraction. Interfaces are used for functions that are not related to objects.

2, multiple inheritance: The PHP class can inherit multiple interfaces, but cannot extend multiple abstract classes.

3, public behavior implementation: The abstract class can be implemented in the common method, but the interface is not.

Iv. Namespaces (PHP6)

Class Library Scripts a.inc.php and script b.inc.php all have a class name named Class CNAME, and the two files are called in the same file, such as index.php. The namespace is used.

Step together:

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

namespace Spacea; and namespace Spaceb; The name is self-determined.

2. When instantiating a class in index.php, prefix the class with a namespace and double colons:
Include ' a.inc.php ';
Include ' b.inc.php ';
$a =new spacea::cname ();
$b =new spaceb::cname ();

This will not be a conflict.
But before the official release of the PHP6, this feature is still undecided.

V. 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> ';
The structure and contents of the output Class A. "PHP Bible" P145;

A detailed summary of PHP class usage

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.