1: Structure and call (instantiation):
class className{}, call: $obj = new className(); When the class has a constructor, parameters should also be passed in. Such as $obj = new className($v,$v2…);
2: Constructor and destructor:
1. The constructor is used for initialization: use __construct(), which can take parameters.
2. But the destructor cannot take parameters (used to perform some operations or functions before deleting a class). The destructor is named __destruct(). At the end of the script execution, the objects in the memory will be destroyed, so there is no need to destruct the function, but some, such as COOKIE, etc., should be destroyed using this function.
Knowledge point: PHP4 also provides a constructor, but it uses a class method with the same name as the class. This approach is still compatible with PHP5. When a class does not contain __construct, it will search for the same name as the class. method, if found, is considered to be a constructor, as follows:
Main family members of the class: properties, methods, constants, static members
3. Class attributes:
There are two methods to assign or get values to the attributes of a class.
1. Use public scope public keyword.
2. Use __set() and __get() to assign and obtain values respectively. The former is called the setter method (setter) or the modification method (mutator), and the latter is called the accessor method (accessor) or the getter method ( getter). It is recommended to use this method: Advantages:
A. Data verification can be performed uniformly in __set().
B. It facilitates unified management of attributes.
Note:
First: __set() and __get() only work on private attributes. For attributes defined with public, they are both lazy, as follows:
Second: __set($n,$v) takes two parameters. And __get($n) can only have one parameter. Example:
4. Class methods:
Just understand it as a function in the class.
Call:
1. Internal call: You can use $this->Fanname(); or $this->addab() or test::addab();
2. When calling instantiation, use $e->addab();. For those that do not use the $this keyword in this method, as in the above example:
function addab() { return $this->a+$this->b; }
is changed to: function addab( ) { return 25; } Then when calling this method on an external instance, you can also use "$e::addab();" or "test::addab();"
5. Class constants:
If the attributes of a class are understood as variables in the class, then the constants and variables of the class are different. The definition method is:
6. Static members of the class (static properties or static methods):
If you need to create fields or methods that are shared by all instances of the class. You have to use static members. There are two characteristics:
1. Static members are communists. They allow all instances of the class on the script to be called, but they cannot be called with the help of a specific instance name of the class. Instead, they use "class name::$ members" outside the class. name". Internally, the class uses "self::$ member name" to call.
2. Each time a new instance is created, the static members will be recalculated from the last value of the last created instance, rather than from the initial value in the class.
3. For static members defined with public, its value can be changed externally. Private etc. will not work.
(2) Double colon "::" keyword: used to call constants and static members.
(3) The self keyword: Used with a double colon to call static members inside a class, such as self::$staticVar. Inside a class, $this cannot be used to call static members.
(4) __toString(): Use __toString() in a class to convert the class into a string and print the class. It is of little use: such as:
(6) __call(): Method overloading, see the following example:
$x='a';
$y=array('a','b');
$b=new cB;
$b->showVarType($x); //Not an array or a number
$b->showVarType($y); //This is an array
(7) extends: inheritance: For example, class a{} class b extends a{} class b inherits class a
Attachment: Remember: In the future, use "-> " when calling methods or properties, and double colon "::" when calling constants, so you won't get confused.
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 subclasses), protected (private, but can be used by subclasses), abstract (abstract, (See below), final (prevents overwriting in subclasses - also called overloading, prevents inheritance, 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):
Abstraction can be understood as the parent class defining a template or base class for the child class. Scope abstract is only declared in the parent class, but implemented in the child class. Note:
1. Abstract classes cannot be instantiated and can only be implemented after being inherited by subclasses (concrete classes).
2. An abstract class must implement all abstract methods of the abstract class in its subclasses. Otherwise something will go wrong.
3. In an abstract method, it is only declared, but cannot be implemented: for example, abstract function gettow(){ return $this->p; } is wrong, and you can only declare this method: abstract function gettow(); (Do not even include square brackets {}). Abstract methods and abstract classes are mainly used in complex class hierarchies. This hierarchy ensures that each subclass contains and overloads certain methods. This can also be achieved via the interface
4. Attributes cannot be named abstract attributes. For example, abstract $p = 5 is wrong.
5. Only classes declared as abstract can declare abstract methods, but if the method is declared as abstract, it cannot be implemented concretely. For example:
6. In an abstract class, if you want to implement specific methods, you cannot declare it as abstract. This may actually be more meaningful. The common parts in several class libraries can be extracted into abstract classes, and other classes can inherit the abstract class. As follows:
function addab(em $j,$c) //This method can be called internally or externally. As long as the scope allows.
{ return $j->k+$c; }
}
$a = new test();
$b = new em();
echo $a-> addab($b,2); //or $a->addab(new em(),2);
1. Instanceof keyword: used to analyze whether an object is an instance or subclass of a certain class or implements a specific interface: as shown in the following example, but please note: The class name does not have any delimiters such as quotation marks. , otherwise an error will occur. If test cannot use 'test'
3. Return class name: string get_class(object). If successful, it will return the class name of the instance. If it fails, it will return FALSE:
$a = new test2(); echo get_class($a); //return test2
4. Understand the public attributes of the class: array get_class_vars(‘className’), returns the key array: containing all defined public attribute names and their corresponding values. This function cannot use instance names as variables
5. Return class methods: get_class_methods('test'); //or: get_class_methods($a); can use instance names as parameters and return all non-private methods including constructors.
6. print_r(get_declared_classes()) learns all the class names in the current PHP version. PHP5 has 149.
7. get_object_vars($a) returns an associative array of all public 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 a parameter, while get_class_vars(‘test’) uses the class name as a parameter.
* (2) The attribute value obtained by get_object_vars($a) is the value after the instance is run, while the attribute 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 attributes. If public $q; is defined in class test, Array ([v] => 5 [q]=>) is returned,
*/
8. Return the name of the parent class: get_parent_class($b);//or get_parent_class(‘test2′); return test
9. Determine whether the interface exists: boolean interface_exists($string interface[,boolean autoload])
10. Determine the object type: boolean is_a($obj,'className'). When $obj belongs to the CLASSNAME class or its subclass, it returns TRUE. If $obj has nothing to do with the class type, it returns FALSE. For example: is_a($a,'test')
11. Determine whether it is a sub-object of a certain class: when $b inherits from the TEST class, return TRUE, otherwise FALSE. boolean is_subclass_of($b,'test');
12. Determine whether a method exists in the class or instance. method_exists($a,'getv') //Or use method_exists('test','getv'). This function is suitable for methods in non-publicly defined scopes.
Example of the above function:
$a=new test();
$b=new test2();
print_r( get_class_methods('test')); //or: print_r( get_class_methods($a)); both return :Array ( [0] => __construct [1] => getv )
echo '
';
print_r( get_class_vars('test')); //Return: Array ( [v] => 2), unlike the above, you cannot use print_r( get_class_methods($a));
echo '
';
echo get_parent_class($b);// Or get_parent_class('test2′); returns test
echo '
';
echo is_a($b,'test');// returns 1
echo '
';
if(is_subclass_of('test2′,'test'))echo 'is a subclass! '; //or (is_subclass_of($b,'test')), returns 1, when parameter 1 is $a, returns false,
echo '
';
echo method_exists( $a,'getv') //Or use method_exists('test','getv') to return 1. This function is also suitable for methods that define domains such as private.
When there are more classes, for example, to load three class library files in one file: a.class.php, b.class.php, c.class.php, three require_once('classes/a .class.php);
require_once(‘classes/b.class.php);
require_once(‘classes/c.class.php);
You can use the PHP5 automatic loading function to handle it: in the global application configuration file, define a special function __autoload($class) function (__autoload is not a method of a class, it is just a separate function and has nothing to do with the class ):
function __autoload($class){
require_once(“classes/$class)
}
It doesn’t matter where the function is placed. There is no need to call this autoload function when creating a class instance. PHP will do it automatically. But be sure to pay attention to one thing: "The class name used to create the instance on the calling page", "The called file name", and "The name of the class in the file" must be the same. In this way, there is no need to call __autoload(); if it is different, you must call __autoload('c'); separately and give it a file name prefix. For example: The code of the
c.class.php file is:
$m = new c(); //The class called when creating the instance is also c
echo $m->m;
?>
But if the code in c.class.php is:
Family extension of class: Advanced functions of class:
1. Object cloning:
When an instance of an object is cloned, its initial attribute value inherits the current value of the cloned object.
Classes that are not declared final can be inherited, methods that are not defined by final and private can also be inherited, and properties that are not defined by private can also be inherited. When a subclass inherits a parent class or superclass, it can directly use all allowed methods and attributes of the parent class or superclass (grandfather class and grandfather's grandfather).
Key: Understand the characteristics of constructors and overloading in inheritance!
(1) Characteristics of constructor in inheritance:
1. When the parent class has a constructor but the subclass does not: the subclass will automatically execute the parent class's constructor when instantiated. At this time, if you want to create an instance of the subclass, you need to introduce the parameters required in the parent class constructor, otherwise an error will occur. Even if the "subclass of a subclass" does not have a constructor, the parameters required by the constructor of its parent class's parent class must be entered when creating an instance. PHP will search upwards from the subclass where the instance is located for a combined constructor, and once it is found, it will stop and use that constructor. It will not search upwards. Therefore: if the subclass itself does not have a constructor, the closest superclass with a constructor shall prevail.
class cB extends cA{
function funB1() { echo ‘
class cC extends cB {
function funC1() { echo '
A. Add parent::__construct($n)
B. Change the constructor in CC to:
1. Call the parent class method: There are 3 methods to call the parent class method in the subclass:
$this->ParentFunction(); or
Parent class name::ParentFunction(); Or
parent::parentFun();
2. Call parent class properties: only use $this->ParentProperty;
(3) Overloading:
In a subclass, you can define the same attributes or methods as those of the parent class, and change the value or operation of the attribute or method of the parent class, which is called overloading. For example:
calss ParClass{ function pfun(){ ….}}
class ChildrenClass extends ParClass{function pfun(){ ….}}} //Overload the pfun method of the parent class.
After overloading in a subclass, the newly defined method or attribute after overloading will be executed first.
You can also use parent::parentFun(); in a subclass to call the method of the parent class, but the value obtained is the parameter operation value entered by the subclass itself. Rather than the value that the method operates on in the parent class.
3. Interface:
Interface: Interface can be understood as a common specification for a set of functions. The greatest significance may be to specify a common method name for their respective development when multiple people collaborate.
Same as abstract method in abstract class:
1. The specific implementation of the method cannot be defined in the interface. Instead, it is implemented by concrete classes (non-abstract methods in abstract classes do not need to be defined, only abstract methods and interfaces are required to be implemented in concrete classes).
2. Like abstract classes, constants can be defined in interfaces and directly inherited by concrete classes.
3. Concrete classes must implement all abstract methods of abstract classes (except non-abstract methods). Similarly, if a concrete class implements an interface through implements, it must complete all methods in the interface.
Interface implementation process: 1. Define the interface, 2. Use ..implement X, Y,... to connect with specific classes.
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, directly call the constant value in the interface.
$age->getN();
1. Relevance: Use abstraction when the created model is adopted by some closely related objects. For functions adopted by unrelated objects, use interfaces.
2. Multiple inheritance: PHP classes can inherit multiple interfaces, but cannot extend multiple abstract classes.
3. Public behavior implementation: Abstract classes can implement public methods in them, but interfaces cannot.
4. Namespace (PHP6)
Both the class library script A.inc.php and the script B.inc.php have a class named class CNAME, and these two files must be called in the same file such as index.php. Namespaces are used at this time.
Buju:
1. Open the two files A and B above, and add one line at the front of each:
namespace SPACEA; and namespace SPACEB; can be customized.
2. When instantiating a class in index.php, add a namespace and a double colon as a prefix in front of the class:
include 'a.inc.php';
include 'b.inc. php';
$a=new SPACEA::CNAME();
$b=new SPACEB::CNAME();
This way there will be no conflict.
But this feature has not yet been finalized before PHP6 is officially released.
5. Implement iterators and iteration.
See P142 of "PHP Bible";
6. Use Reflection API.
Simple example:
class a{ …. }
$c = new ReflectionClass(‘a’); //PHP built-in class.
echo '
'.$c.'';