PHP class usage and summary

Source: Internet
Author: User
Tags autoload class manager getv

1. Structure and call (instantiation ):

Class className {}, call: $ obj = new className (); when the class has a constructor, you should also input parameters. For example, $ obj = new className ($ v, $ v2 ...);

2. constructor and destructor:
1. constructor for initialization: Use _ construct (), which can contain parameters.
2. But the Destructor cannot contain parameters (used to perform some operations or functions before a class is sold ). The Destructor uses _ destruct () as the name. At the end of the script execution, the objects in the memory will be sold out, so you do not need to analyze the function. However, for some objects such as cookies, you should use this function to sell out.
Knowledge Point: constructor is also provided in PHP4, but a class method with the same name as the class is used. PHP5 is still compatible with this method. When a class does not contain _ construct, it will look for methods with the same name as the class. If it is found, it is considered as a constructor, 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 call the constructor of the parent class (the constructor overload is not supported). It must be explicitly called using the parent keyword.
Class employee {
Function _ construct ()....
}
Class Manager extents Employee {
Function _ construct (){
Parent: _ construct ();
Echo 'the parent class constructor of this subclass has been called! ';
}
}
You can also call constructors of other classes that are irrelevant to the instance. You only need to add the class name before _ construct. For example:
OtherClassName ::__ construct ();

Main family members of the class: attributes, methods, constants, and static members

Iii. class attributes:
There are two ways to assign values to the attributes of a class.
1. Use the public keyword in the public scope.
2. Use _ set () and _ get () to assign values respectively. The former is called setter or mutator ), the latter is called an access method or a getter ). This method is recommended. Advantages:
A. data verification can be performed in A unified manner in _ set.
B. It is convenient to manage attributes in a unified manner.
Note:
First :__ set () and _ get () Act only on private attributes. For attributes defined by public, both of them are lazy, as shown below:
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"
"; Echo $ a-> B;
For $ a, $ B, and $ c, the instance is filtered and returned through _ set and _ get. For $ d, the instance does not work. For example, $ a-> d = 5, and then return 5.
Second :__ set ($ n, $ v) must contain two parameters. But _ get ($ n) can have only one parameter. Instance:
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 it is changed to return $ this-> $ name + $ this-> addab (); for example, call the value of, the actual returned value is a + B. The default value is 5 + 5 + 6 = 16.
}
Function addab ()
{Return $ this-> a + $ this-> B ;}
}
$ E = new test ();
$ E-> a = 11; // Note: $ this-> $ n is used inside the class to write the variable, but $ e-> a is used for external instances.
$ E-> B = 12; // get 14
$ E-> k = 22;

The attributes of a class can be freely expanded. Whether or not _ set is used for k in the preceding example, you can use $ e-> newProperty = xx after an instance is created; directly create an attribute, but it is not recommended to do so.

Iv. Class methods:
It can be understood as a function in the class.
Call:
1. Internal call: You can use $ this-> Fanname (); or $ this-> addab () or test: addab ();
2. When calling an instance, use $ e-> addab. If the $ this keyword is not used in this method, in the example above:
Function addab () {return $ this-> a + $ this-> B ;}
Change to: function addab () {return 25;}. If this method is called on an external instance, you can also use "$ e: addab ();" or "test: addab ();"

5. constants of the class:
If the attributes of a class are interpreted as variables in the class, the constants and variables of the class are different. The definition method is as follows:
Class test {
Private $;
Const PI = '3. 14 ′;
.....
// Call the above constant in the class using two methods, "$ this: PI", or "Class Name: PI". Here is test: PI, as shown below:
Function getvalue (){
Return $ this-> a * $ this: PI; // or $ this-> a * test: PI. You can use the this keyword or class name, however, both use double colons.
}
}
$ E = new test ();
$ E-> PI = 5; // Note: Here-> is used to create an attribute named PI, rather than changing the value of the PI constant in the class.
Echo $ e: PI; // This is the constant of the call class.
Constants can only be called with double colons. And its value cannot be changed.
There are also two methods to call class constants after class external instantiation. Method:
"$ E: PI" or "test: PI", both use colons. The difference is that the this keyword cannot be used externally, but only the Instance name can be used, but the class name is :: PI is generic.

6. Static members of a class (static attributes or static methods ):
If you want to create a field or method shared by all classes of the instance. You must use static members. There are two features:
1. The static member is a communist who calls all the instances of the class in the script, but cannot call the instance by the specific instance name of the class. Instead, the class name is used outside the class:: $ member name. The class is called using the "self: $ member name.
2. When each new instance is created, the static member will re-calculate from the last value of the last instance, instead of the initial value in the class.
3. The value of a static member defined by public can be changed externally. Private.
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; // The value of the static member is changed due to the public defined member.
$ C = new test ();
Echo test: getV (); // return 9

VII. Keywords:
(1) this Keyword: used internally to refer to the class itself. To access attributes, methods, or constants, such as $ this-> attribute name or method name. $ This: constant name. This can also be used in subclass of this class to refer to its own attributes or methods.
(2) Double colon ":" Keyword: Used to call constants and static members.
(3) self Keyword: static members can be called in combination with double colons in the class, such as self ::$ staticVar... in the class, $ this cannot be used to call static members.
(4) _ toString (): Use _ toString () in the class to convert the class into a string and print the class. It is of little use, for example:
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 echo $ a->__ toString ();
(5) _ clone (): This keyword takes effect only when the object is cloned. It is used to change some values during cloning.
(6) _ call (): Method overload. The parameters are as follows:
Class cB {
Function _ call ($ method, $ n ){
If ($ method = 'showvartype '){
If (is_numeric ($ n [0]) {// $ n cannot be used. Use $ n [0];
$ This-> displayNum ();
} Else if (is_array ($ n [0]) {
$ This-> displayArr ();
} Else {
$ This-> displayOther ();
}
}
}
Function displayNum (){
Echo 'This is a number! ';
}
Function displayArr (){
Echo 'This is an array! ';
}
Function displayOther (){
Echo 'is neither an array nor a number! ';
}
}

$ X = 'a ';
$ Y = array ('A', 'B ');
$ B = new cB;
$ B-> showVarType ($ x); // It is neither an array nor a number.
$ B-> showVarType ($ y); // This Is An Array
Note: The showVarType () method cannot be defined in the class; otherwise, the Code cannot be used.
(7) extends: inheritance: for example, class a {} class B extends a {} class B inherits class

Note: in the future, "->" will be used to call a method or attribute, and ":" will be used to call a constant, so it will not be dizzy.

8. Scope of methods and attributes:
There are 6 types: public (default, can be omitted, also equivalent to the var declaration of php6), private (private, cannot be used by subclass), protected (private, but can be used by subclass), abstract (abstract, parameter below), final (to prevent overwriting in subclass-also weigh load, to prevent being inherited, used to modify class names and methods, such as final class test {final function fun () {}}, but cannot be used for attributes), static (static)

9: abstract classes and abstract methods (abstract -- Note: There is no so-called abstract attribute ):
Abstract: The parent class defines a template or base class as a subclass. The scope abstract is only declared in the parent class, but is implemented in the subclass. Note:
1. abstract classes cannot be instantiated. They can only be implemented after the quilt class (specific class) is inherited.
2. the abstract class must implement all abstract methods of the abstract class in its subclass. Otherwise, an error occurs.
3. In an abstract method, it is only a declaration, but cannot be implemented. For example, abstract function gettow () {return $ this-> p;} is incorrect. Only this method can be declared: abstract function gettow (); (do not show braces {}). abstract methods and abstract classes are mainly used in complex class hierarchies. This hierarchical relationship must ensure that each subclass contains and reloads certain methods. This can also be implemented through the interface
4. Attributes cannot be named abstract attributes. For example, abstract $ p = 5 is incorrect.
5. Only the declared abstract class can declare the abstract method. However, if the declared method is abstract, it cannot be implemented in detail. For example:
Abstract class Employee
{
Abstract function (...);
Abstract function B (...);
}
In the future, this parent class will be extended to form various sub-classes (such as managers, employees, and cashiers ).
6. to implement a specific method in an abstract class, it cannot be declared as abstract. This may be more practical. You can extract the common parts of several class libraries to the abstract class. Other classes can inherit the abstract class. As follows:
Abstract class BaseShop {
Const TAX = 0.06; // define a constant in an abstract class
Public function buy ($ gid) {// if it is defined as an abstract function buy (), the subject cannot be implemented here.
Echo ('item with ID: '. $ gid.' You purchased ');
}
Public function compute ($ gid ){
Echo ('item with ID: '. $ gid.' You sold ');
}
Public function view ($ gid ){
Echo ('the item with ID: '. $ gid.' You viewed ');
}
}
Class BallShop extends BaseShop {
Var $ itme_id = null;
Public function _ construct ()
{
$ This-> itme_id = 2314;
}
Public function open ()
{
$ This-> require ($ this-> itme_id );
}
Public function getTax ()
{
Echo printf ('average tax rate is % d %. ', $ This: TAX * 100 );
}
}
$ S = new BallShop;
$ S-> open (); // you have sold the product ID: 2314
$ Shop-> getTax ();

10: Type prompt:
Note: The type prompt function can only be used for prompts where the parameter is an object, but cannot be used for prompts of integer, String, floating point, and other types. Some class methods need to pass in the parameter as the expected object type, you can use the following method to achieve forced implementation of this alternative. To reach the type prompt, you only need to add an existing class name before the object type parameter of the method, such as: function funname (OtherClassName $ otherclassINSName, $ c ....), Note that OtherClassName must be an existing class. As follows:
Class em {var $ k = 56 ;}
Class test {
Function _ construct ()
{Echo $ this-> addab (new em (), 2 );}

Function addab (em $ j, $ c) // This method can be called internally or externally. As long as the scope permits.
{Return $ j-> k + $ c ;}
}
$ A = new test ();
$ B = new em ();
Echo $ a-> addab ($ B, 2); // or $ a-> addab (new em (), 2 );

11. Class Management:
1. instanceof Keyword: used to analyze whether an object is an instance or subclass of a class or to implement a specific interface. For example, note that the class name does not have any delimiters such as quotation marks, otherwise, an error occurs. For example, test cannot use 'test'
Class test2 {}
Class test {}
Class testChilern Extends test {}
$ A = new test2 ();
$ M = new test ();
$ I = ($ m instanceof test );
If ($ I) echo '$ m is an instance of the test class!
'; // Get this value
Switch ($ a instanceof test ){
Case true:
Echo 'Yes
';
Break;
Case false:
Echo 'no
'; // Get this value
Break;
}
$ D = new testChilern ();
If ($ d instanceof test) echo '$ d is a subclass of the test class!
'; // Get this value
2. Determine whether the class exists: boolean class_exists (string class_name): class_exists ('test ');
3. Return Class Name: string get_class (object). If the call succeeds, the instance class name is returned. If the call fails, FALSE is returned:
$ A = new test2 (); echo get_class ($ a); // return test2
4. Understand the common attributes of the class: array get_class_vars ('classname'), and return the key array: containing all the defined public attribute names and their corresponding values. This function cannot be used as a variable by instance name.
5. Return class method: get_class_methods ('test'); // or: get_class_methods ($ a); Use the Instance name as a parameter and return all non-private methods including constructors.
6. print_r (get_declared_classes () describes all the class names in the current PHP version. There are 149 PHP5 instances.
7. get_object_vars ($ a) returns the associated arrays of all common attributes and their values in the instance. Note the difference between it and get_class_vars:
/* (1) get_object_vars ($ a) uses the Instance name as the parameter, while get_class_vars ('test') uses the class name as the parameter.
* (2) the property value obtained by get_object_vars ($ a) is the value after the instance runs, while the property value obtained by get_class_vars ('test') is the initial definition in the class.
* (3) both return the associated array, and return the NULL value for the unassigned attribute. If public $ q is defined in class test, Array ([v] => 5 [q] =>) is returned ),
*/
8. Return the parent class name: get_parent_class ($ B); // or get_parent_class ('test2'); return test
9. Check whether the interface exists: boolean interface_exists ($ string interface [, boolean autoload])
10. Determine the object type: boolean is_a ($ obj, 'classname'). If $ obj belongs to the className class or belongs to its subcategory, TRUE is returned, if $ obj is irrelevant to the class type, FALSE is returned. For example: is_a ($ a, 'test ')
11. determine whether it is a certain type of sub-object: If $ B is inherited from the TEST class, TRUE is returned; otherwise, FALSE is returned. Boolean is_subclass_of ($ B, 'test ');
12. check whether a method exists in the class or instance. Method_exists ($ a, 'getv') // or use method_exists ('test', 'getv'). This function is applicable to non-public-defined scope methods.
The above function example:
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); return: array ([0] => _ construct [1] => getv)
Echo'
';
Print_r (get_class_vars ('test'); // return: Array ([v] => 2). Unlike the above, print_r (get_class_methods ($ a) cannot be used ));
Echo'
';
Echo get_parent_class ($ B); // or get_parent_class ('test2'); return test
Echo'
';
Echo is_a ($ B, 'test'); // return 1
Echo'
';
If (is_subclass_of ('test2', 'test') echo 'is a subclass! '; // Or (is_subclass_of ($ B, 'test'). 1 is returned. If parameter 1 is $ a, false is returned,
Echo'
';
Echo method_exists ($ a, 'getv') // or use method_exists ('test', 'getv') to return 1. This function is also applicable to fixed domain methods such as private.

11. automatically load the class library file:
When there are more classes, for example, you need to load three class library files in one file:. class. php, B. class. php, c. class. php should use three require_once ('classes/. class. php );
Require_once ('classes/B. class. php );
Require_once ('classes/c. class. php );
You can use the PHP5 Automatic Loading Function to handle the problem: in the global application configuration file, define a special function _ autoload ($ class) function (_ autoload is not a class method, but a separate function. It has nothing to do with the class ):
Function _ autoload ($ class ){
Require_once ("classes/$ class)
}
It does not matter where the function is stored. You do not have to call this autoload function when creating a class instance. PHP will automatically complete. Note that: the "Name of the class used to create an instance on the call page", "called file name", and "Name of the class in the file" must be the same. In this way, you do not need to call _ autoload (). Otherwise, you must call _ autoload ('C') separately and give it a prefix of the file name. For example:
The code for the c. class. php file is:
Class c {
Public $ m = 7;
}
?> Here, the Class Name of the Code is c, and the file name is c,
Now you need to call index. php:
Function _ autoload ($ class ){
Require_once "$ class. class. php ";
}

$ M = new c (); // The class called to create an instance is also c
Echo $ m-> m;
?>
PHP automatically calls class c in C. class. php under the root directory.

However, if the code in c. class. php is:
Class mm {
Public $ m = 7;
}
?>
The call page index. php code is:
Function _ autoload ($ class ){
Require_once "$ class. class. php ";
}
# _ Autoload ('C'); // an error occurs if this line is not added.
$ M = new mm ();
Echo $ m-> m;
?>
An error occurs and the mm. class. php file cannot be found. In this case, you can add a line of _ autoload ('C'), but this will not simplify the code.

Family extension of the class: advanced features of the class:

1. Object cloning:
When an instance of the cloned object is cloned, its initial attribute values inherit the current value of the object to be cloned.
Class test
{
Public $ p = 5;
Function _ clone () {// only takes effect when cloning occurs. Used to change some values during cloning
$ This-> p = 15;
}
}
$ A = new test ();
Echo $ a-> p;
$ A-> p = 8; // If the _ clone () method is not affected, the p value of $ B is 8.
$ B = clone $;
Echo $ B-> p; // 15

Ii. Object Inheritance:

Classes that are not declared as final can be inherited, 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. After the subclass inherits the parent class or superclass, you can directly use all allowed methods and attributes of the parent class or superclass (grandfather class and grandfather's grandfather.
Key: Understanding the features of constructor and overload in inheritance!
(1) features of constructor in inheritance:
1. When the parent class has a constructor and the Child class does not: the Child class automatically executes the constructor of the parent class during instantiation. If you want to create a subclass instance, You need to introduce the parameters required by the parent class constructor. Otherwise, an error occurs. Even if there is no constructor for the subclass, you must enter the required parameters for the constructor of the parent class when creating the instance. PHP searches for the combined constructor from the subclass where the instance is located. Once found, the constructor is stopped and used. Instead, it will not search up. Therefore, if the subclass itself does not have a constructor, it is subject to a superclass with the closest constructor.
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 cB execute success! ';}
}

Class cC extends cB {
Function funC1 () {echo 'class cC FunC1! ';}
}
$ B = new cB ('jack ');
$ B-> name = 'john ';
Echo "$ B-> name: $ B-> age ";
$ B-> funB1 ();
$ C = new cC (); // an error occurs here. Because cB does not have a constructor, take the cA as the standard. A parameter is required. Change to $ c = new cC ('David.
Echo $ c-> name (); // David
2. When a subclass also has a constructor: At this time, no matter whether the parent class has a constructor or not, the subclass's own constructor will be executed.
As shown above:
Class cB extends cA {
Function _ construct (){
Echo 'this is Class cB \'s _ construct! ';
}
Function funB1 (){
Echo 'class cB execute success! ';
}
}
When class CB has its own constructor, the instance $ B = new cB ('jack') is created. The parameter Jack does not work because the constructor of the parent class CA is not executed. Therefore, $ B-> name and $-> age do not initialize values. You need to assign $ B-> name = 'jack', $ B-> age = 25;
If you want to execute the constructor of the parent class CA, you can:
Function _ construct ($ n ){
Parent ::__ construct ($ n); // or: cA ::__ construct ($ n );
Echo 'this is Class cB \'s _ construct! ';
}
Because parent ::__ construct ($ n); only the constructor of the parent class is searched up. Once found, the constructor is stopped and executed. Therefore, in the preceding example, if parent ::__ construct ($ n) is used in the class cC at the last layer, and CB and CA have constructors, then the cC instance only executes the cB constructor. CA is not executed. At this time, if the CC instance wants to call both the constructor CA and CB, there are two methods:
A. Add parent :__ construct ($ n) to CB)
B. Change the constructor in CC:
Function _ construct ($ n ){
CA ::__ construct ($ n); // Class Name: constructor.
CB: :__ construct ();
Echo 'this is Class cB \'s _ construct! ';
}
(2) Calling the attributes or methods of the parent class in the subclass:
1. Call the parent class method: Call the parent class method in the subclass. There are three methods:
$ This-> ParentFunction (); or
Parent Class Name: ParentFunction (); or
Parent: parentFun ();
2. Call the parent class property: You can only use $ this-> ParentProperty;
(3) heavy load:
In a subclass, you can define the same attributes or methods as the parent class, and change the value or operation of this attribute or method of the parent class, which is called as overload. For example:
Calss ParClass {function pfun (){....}}
Class ChildrenClass extends ParClass {function pfun (){....}}} // Overload the pfun method of the parent class.
After a new method or attribute is reloaded in a subclass, the newly defined method or attribute is preferentially executed.
You can also use parent: parentFun (); In the subclass to call the method of the parent class, but the obtained value is the parameter operation value entered by the subclass itself. Instead of the value calculated by this method in the parent class.

Iii. interface:

Interface: interface, which can be understood as the common specification of a set of functions. The greatest significance may be to define a common method name for each development when multiple people collaborate.
Same as abstract methods in abstract classes:
1. the specific implementation of the method cannot be defined in the interface. It is implemented by a specific class. (non-abstract methods in an abstract class do not need to be defined. Only Abstract methods and Interfaces must be implemented in a specific class ).
2. Like abstract classes, constants can be defined in interfaces and directly inherited by specific classes.
3. A specific class must implement all abstract methods of the abstract class (except non-Abstract METHODS). Similarly, a specific class must complete all methods in the interface after implementing the interface through implements.

Interface implementation process: 1. Define the interface; 2. Use .. implement X, Y ,... Connect to a specific class.
Interface Info {// define an interface
Const N = 22;
Public function getage ();
Public function getname ();
}

Class age implements Info // if you want to use multiple interfaces class age (extends emJob) implements Info, interB...
{
Public $ age = 15;
Public $ name = 'join ';
Function getage (){
Echo "the grade is $ this-> age ";
}
Function getname (){
Echo "name is $ this-> name ";
}
Function getN (){
Echo 'the value of constant N defined in the interface is:'. $ this: N. ''; // directly inherits the constant value from the interface.
}
}

$ Age = new age;
Echo $ age: N; // 22. Call the constant value in the interface directly.
$ Age-> getN ();
Differences between abstract classes and interface classes: when to use interfaces and when to use abstraction?
1. Relevance: Use abstraction when the created model is used by closely related objects. Interfaces are used for functions of irrelevant objects.
2. Multi-inheritance: the PHP class can inherit multiple interfaces, but cannot extend multiple abstract classes.
3. Public Behavior implementation: abstract classes can implement public methods, but interfaces cannot.

4. namespace (PHP6)

Class Library scripts A. inc. php and script B. inc. php both have class names as class CNAME, and these two files must be called in the same file, such as index. php. In this case, the namespace is used.
Steps:
1. Open the above files A and B and add A line at the beginning of the above:
Namespace SPACEA; and namespace SPACEB; Name customization.
2. when instantiating a class in index. php, add the namespace and double colon as the prefix before the class:
Include 'a. inc. php ';
Include 'B. inc. php ';
$ A = new SPACEA: CNAME ();
$ B = new SPACEB: CNAME ();
In this way, there will be no conflict.
However, before the official release of PHP6, this function was not fixed yet.

5. Implement iterator and iteration.
Participate in PHP Bible P142;

6. Use the Reflection API.
Simple instance:
Class {.... }
$ C = new ReflectionClass ('A'); // PHP built-in class.
Echo'

’.$c.’
';
The structure and content of the output Class. Participate in PHP Bible P145;

Reprint: http://www.onexin.net /? P = 2533

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.