Use and summary of PHP classes_PHP tutorial

WBOY
Release: 2016-07-13 17:18:37
Original
1053 people have browsed it

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 script execution, the objects in the memory will be destroyed, so there is no need to destruct the function, but some, such as COOKIE, should be destroyed using this function.
Knowledge point: PHP4 also provides a constructor, but 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 a method with the same name as the class. If found, it is considered to be 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 will not automatically call the constructor of the parent class (constructor overloading is not supported) and must be called explicitly using the parent keyword.
class employee{
function __construct()….
}
class Manager extents Employee{
function __construct(){
parent::_construct();
echo ‘The parent class constructor of this subclass was called! ’;
}
}
Of course, you can also call constructors of other classes that have nothing to do with the instance. Just add the class name before __construct(). Such as:
otherClassName::__construct();

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

3. Class attributes:
There are two ways to assign or get values ​​to attributes of a class.
1. Use the public keyword in public scope.
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 getter method (getter). It is recommended to use this method: Advantages:
A. Data verification can be performed uniformly in __set().
B. Facilitate 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:
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;
In the example, only the settings for $a, $b, and $c will be filtered and returned through __set and __get. For $d, it will not work. For example, $a->d=5, it will still return 5.
Second: __set($n,$v) takes two parameters. And __get($n) can only have one parameter. Example:
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 changed 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 writing: $this->$n is used inside the class, that is, the variable is written, but $e->a is used for external instances.
$e->b = 12; //get 14
$e->k = 22;

The attributes of a class can be freely extended, as shown in the above example k. Regardless of whether __set is used or not, when an instance is established, you can use $e->newProperty = xx; to directly create an attribute, but this is not recommended.

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 instantiating the call, 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; }
Change 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:
class test{
private $a;
const PI = ’3.14′;
…..
//There are two methods to call the above constants in the class, "$this::PI", or "class name::PI", here is test::PI, as follows:
function getvalue(){
return $this->a * $this::PI; //or $this->a * test::PI, you can use the this keyword or the class name, but you must use double colons.
}
}
$e= new test();
$e->PI =5; //Note that using -> here only creates an attribute also named PI, rather than changing the value of the PI constant in the class.
echo $e::PI; //This is the constant of the calling class.
Constants can only be called using double colon::. And its value cannot be changed.
There are also two ways to call class constants after instantiation outside the class. The method is:
"$e::PI" or "test::PI", the common point is that they both use a colon, the difference is that the this keyword cannot be used externally, only the instance name can be used, but the class name::PI is universal.

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 call them, but they cannot be called with the help of a specific instance name of the class. Instead, they use "class name::$member name" outside the class. method call. 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, not 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.
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; //Change the value of the static member due to the public defined member.
$c = new test();
echo test::getV(); // Return 9

7. Keywords:
(1) This keyword: used internally to refer to the class itself. To access properties, methods or constants, such as $this->property name or method name. $this::constant name. this can also be used in subclasses of this class to refer to its own properties or methods.
(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:
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();
(5) __clone(): This keyword will only take effect when the object is cloned, and is used to change certain values ​​during cloning.
(6) __call(): Method overloading, see the following example:
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 not an array or a number!

’;
}
}

$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
Note that the showVarType() method cannot be defined in the class, otherwise the code will not work.
(7) extends: inheritance: such as class a{} class b extends a{} class b inherits class a

Attachment: Memory: 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 in total: public (default, can be omitted, also equivalent to the var statement 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 class and abstract method (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. You can only declare this method: abstract function gettow(); (with square brackets) {} do not appear), abstract methods and abstract classes are mainly used in complex class hierarchical relationships. 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. Such as:
abstract class Employee
{
abstract function a(…);
abstract function b(…);
}
Later, this parent class will be expanded to form various subclasses (such as managers, employees, cashiers).
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:
abstract class BaseShop{
Const TAX=0.06; // Define constants in abstract classes
public function buy($gid) { // If defined as an abstract method abstract function buy() cannot implement the body here.
echo(‘You purchased the product with the ID:’.$gid.’);
}
public function sell($gid) {
echo(‘You sold the product with the ID:’.$gid.’);
}
public function view($gid) {
echo(‘You viewed the product with the 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(‘

The average tax rate is %d%%.

’,$this::TAX*100);
}
}
$s = new BallShop;
$s->open(); //You sold the product with ID :2314
$shop->getTax();

Ten: Type Tip:
Note that the type hint function can only be used for hints whose parameters are objects, and cannot be used for type hints such as integers, strings, floating point, etc. Some class methods require that the parameters passed in be the expected object type. You can use the following method to enforce this alternative. To achieve type hinting, just add the name of an existing class before the object 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 allows.
{ 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 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 it will Something went wrong. 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 class test!
’; // 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 class test!
’; // get this value
2. Determine whether the class exists: boolean class_exists(string class_name): class_exists(‘test’);
3. Return the 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 a 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; then 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:
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)); both return: Array ( [0] => __construct [1] => getv )
echo ‘
’;
print_r( get_class_vars(‘test’)); //Return: Array ([v] => 2), different from the above, you cannot use print_r( get_class_methods($a));
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’)), 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 use private and other domain definitions.

11. Automatically load class library files:
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, and 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. Such as:
The code of the c.class.php file is:
class c{
public $m=7;
}
?>The class name of the code here is c, and the file name is also c,
Now call it in index.php:
function __autoload($class){
require_once “$class.class.php”;
}

$m = new c(); //The class called when creating an instance is also c
echo $m->m;
?>
At this time, PHP will automatically call class C in c.class.php in the root directory.

But if the code in c.class.php is:
class mm{
public $m=7;
}
?>
The calling page index.php code is:
function __autoload($class){
require_once “$class.class.php”;
}
# __autoload(‘c’); //If you don’t add this line, an error will occur.
$m = new mm();
echo $m->m;
?>
An error will occur, indicating that the mm.class.php file cannot be found. At this time, you can add a line of __autoload(‘c’); but this will not achieve the purpose of simplifying the code.

Family extension of class: Advanced functions of class:

1. Object cloning:
When an instance of an object is cloned, its initial property values ​​inherit the current values ​​of the cloned object.
class test
{
public $p=5;
function __clone(){ //Only works when cloning occurs. Used to change certain values ​​during cloning
$this->p=15;
}
}
$a=new test();
echo $a->p;
$a->p=8; //If there is no __clone() method, the P value of $b will be 8
$b = clone $a;
echo $b->p; //15

2. Object inheritance:

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 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(); //There will be an error here. Since cB does not have a constructor, it will be based on cA and requires a parameter. Change it to $c=new cC(‘David’);.
echo $c->name(); //David
2. When the subclass also has a constructor: At this time, regardless of whether the parent class has a constructor, the subclass's own constructor will be executed.
As above:
class cB extends cA{
function __construct() {
echo ‘

this is Class cB ’s __construct!

’;
}
function funB1() {
echo ‘

Class cB execute success!

’;
}
}
Now when class CB has its own constructor, create an instance $b=new cB(‘Jack’); the parameter JACK will not work because the constructor of the parent class CA has not been executed. Therefore $b->name and $->age will not initialize the value. Need to assign additional values ​​$b->name=’Jack’, $b->age=25;
If you want to execute the constructor of the parent class CA at this time, you can do this:
function __construct($n) {
parent::__construct($n); // or: cA::__construct($n);
echo ‘

this is Class cB ’s __construct!

’;
}
Since parent::__construct($n); will only search upward for the constructor of the parent class, it will stop once found and execute the currently found constructor. Therefore, in the above example, if parent::__construct($n) is used In the last layer of class cC, and classes CB and CA have constructors, then instances of cC will only execute the constructor of cB. cA will not be performed. At this time, if the instance of CC wants to call the constructors of both CA and CB, there are two methods:
A. Also add parent::__construct($n)
to CB B. Change the constructor in CC to:
function __construct($n) {
cA::__construct($n); //That is: class name::constructor.
cB::__construct();
echo ‘

this is Class cB ’s __construct!

’;
}
(2) Call the attributes or methods of the parent class in the subclass:
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 $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 attributes or methods 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, the newly defined method or attribute after its own 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 input 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 methods in abstract classes:
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. The concrete class must implement all abstract methods of the abstract class (except non-abstract methods). Similarly, if the concrete class implements the 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.
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 "The name is $this->name";
}
function getN(){
echo ‘

The value of the constant N defined in the interface is:’.$this::N.’

’; //Directly inherit the constant value in the interface.
}
}

$age=new age;
echo $age::N; //22, directly call the constant value in the interface.
$age->getN();
Regarding the difference between abstract classes and interface classes: When to use interfaces and when to use abstractions?
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 a line at the front of each:
namespace SPACEA; and namespace SPACEB; have custom names.
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 before PHP6 is officially released, this feature has not been finalized.

5. Implement iterators and iteration.
See "PHP Bible" P142;

6. Use Reflection API.
Simple example:
class a{ …. }
$c = new ReflectionClass(‘a’); //PHP built-in class.
echo ‘

’.$c.’
Copy after login
’;
Output the structure and content of class a. See "PHP Bible" P145;

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

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/621646.htmlTechArticle1: Structure and call (instantiation): class className{}, call: $obj = new className() ;When the class has a constructor, parameters should also be passed in. For example, $obj = new className($v,$v2…); 2: Construct...
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template