Detailed summary of the usage of php class_PHP tutorial

WBOY
Release: 2016-07-13 10:26:02
Original
951 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 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:

Copy code The 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); // Return 9

3. PHP will not automatically call the constructor of the parent class (constructor is not supported) Function overloading) must be called explicitly using the parent keyword.
Copy code The code is as follows:

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

Copy the code The 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 “
”; 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:

Copy code The 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 instead 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 the class can be freely extended, such as k in the above example, regardless of Whether to use __set or not, after an instance is created, you can use $e->newProperty = xx; to directly create a property, 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 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:

Copy code The code is as follows:

class test{
private $a;
const PI = '3.14';
…..
//There are two ways to call the above constant 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 just creates an attribute also named PI , instead of 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 with 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 colons are used. The difference is that the this keyword cannot be used externally, and 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 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.

Copy code The 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 (); // Return 1
$b = new test();
echo test::getV(); // Return 2
test::$v=8; //Due to public definition member, change the value of a static 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:

Copy Code The 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( );

(5) __clone(): This keyword only takes effect when an object is cloned and is used to change certain values ​​during cloning.

(6) __call(): Method overloading, see the following example:

Copy code The code is as follows:

class cB{
function __call($method,$n){
if($method=='showVarType'){
if(is_numeric($n[0])){ //Cannot use $ n. To 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: 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:

Copy code The code is as follows:

abstract class Employee
{
abstract function a(…) ;
abstract function b(…);
}

This parent class will be expanded in the future 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:

Copy code The code is as follows:

abstract class BaseShop{
Const TAX=0.06; // In abstraction Constants defined in the class
public function buy($gid) { // If it is defined as an abstract method abstract function buy(), the body cannot be implemented here.
echo('You bought the product with the ID: '.$gid.');
}
public function sell($gid) {
echo('You sold the product with the ID:'.$gid.'); '.$gid.' product');
}
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 Tips:
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:
Copy code The 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 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 an error will occur. If test cannot use 'test'

Copy the code The code is as follows:

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

Copy code The 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)); 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.


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

Copy the code The code is as follows:

< ?php
class c{
public $m=7;
}
?>

The class name of this code is c, and the file name is also c,
now needs to be called in index.php:
Copy the code The code is as follows:

< ?php
function __autoload($class){
require_once “$class.class.php”;
}

$m = new c(); //The class called when creating the 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:

Copy the code The code is as follows:

< ? php
class mm{
public $m=7;
}
?>

The calling page index.php code is:
Copy code The code is as follows:

< ?php
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;
?>

will error, prompting 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 attribute value inherits the current value of the cloned object.

Copy code The code is as follows:

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.

Copy code The 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 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 will be executed own constructor.
As above:
Copy code The code is as follows:

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 at this time $b=new cB('Jack'); parameters JACK will not work because the constructor of the parent class CA is not executed. Therefore $b->name and $->age will not initialize the value. You 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:
Copy code The code is as follows:

function __construct($n) {
parent::__construct($n); // or: cA::__construct($n);
echo '

this is Class cB 's __construct!

';
}

Because parent::__construct($n); will only search upward for the constructor of the parent class, and stop once it is found. Execute the currently found constructor, so in the above example, if parent::__construct($n) is used in the last level class cC, and classes CB and CA have constructors, then the instance of cC will only execute 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. Add parent::__construct($n)
B. Change the constructor in CC to:

Copy code The code is as follows:

function __construct($n) {
cA::__construct($n); //That is: class name::constructor.
cB::__construct();
echo '

this is Class cB 's __construct!

';
}

(2) Call the properties 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 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.

Copy code The 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 '

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

'; //directly Inherit constant values ​​from interfaces.
}
}

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


About 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 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.'
';
Output the structure and content of class a. See "PHP Bible" P145;

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/824842.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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!