2010 The essence of the latest PHP class summary of the 1th/2 page _php tips

Source: Internet
Author: User
Tags class manager inheritance php class getv
One: Structure and invocation (instantiation):

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

two: constructors and destructors
1. Constructors for initialization: using __construct (), with parameters.
2, but destructors cannot take parameters (used to perform some operations or functions before a class is sold). The destructor is named with __destruct (). At the end of the script execution, PHP will pin out the objects in memory, so you don't have to make a function, but some, such as cookies, should be sold out with this function.
Knowledge Points: Constructors are also provided in PHP4, but using class methods with the same name as the class, which can still be compatible with PHP5, when a class does not contain __construct, it looks for a method with the same name as the class, which, if found, is considered 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 invoke the constructor of the parent class (constructors overload is not supported) and must be explicitly invoked using the parent keyword.
Class employee{
function __construct () ....
}
Class Manager Extents employee{
function __construct () {
Parent::_construct ();
Echo ' The parent class constructor of this subclass is called! ';
}
}
Of course, you can also invoke constructors for other classes that have no relationship to the instance. Just precede the __construct () with the class name. Such as:
Otherclassname::__construct ();

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

third, the properties of the class:
There are two ways to assign or take a value on a class's properties.
1. Use public domain keywords.
2, using __set () and __get () to assign values and values respectively, the former is called Set method (setter) or modify method (Mutator), the latter is called access method (accessor) or Get method (getter). This approach is recommended: advantages:
A, can be in __set () unified data validation.
B, easy to unify management attributes.
Attention:
First: __set () and __get () only work on private properties, and two of them are lazy for properties defined with public, as follows:
Class test{
Protected $a =9, $b =2, $c;
Public $d;
function __set ($n, $v) {$this-> $n = $v +2;}
function __get ($name) {return $this-> $name +2;}
}
$a = new test ();
$a->b = 5;   echo "<br/>"; Echo $a->b;
Instances are only for $a, $b, $c settings are filtered and returned by __set and __get, and for $d, it will not work. such as $a->d=5, return or 5.
Second: __set ($n, $v) to take two parameters. __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 you change to return $this-> $name + $this->addab (); If you call the value of a, the value of A+a+b is actually returned. Default is 5+5+6=16.
}
function Addab ()
{return $this->a + $this->b; }
}
$e =new test ();
$e->a = 11; Note: The internal use of $this-> $n that is the variable, but the external instance to use the $e->a way.
$e->b = 12; Get 14
$e->k = 22;

The properties of a class can be expanded freely, as in the case of the above example K, whether or not using __set, when an instance is established, you can use $e->newproperty = XX to create a property directly, but not recommended.

Four, the class method:
is understood as a function within a class.
Call:
1, internal call: You can use $this->fanname (); or $this->addab () or Test::addab ();
2. When the call is instantiated, use $e->addab (); For those that do not use the $this keyword in this method, as in the previous example:
function Addab () {    return $this->a+ $this->b;    }
Changed to: function Addab () {    return 25;   } that method is invoked in an external instance, and can also be used "$e:: Addab ();" or "Test::addab ();"

Five, class constants:
If the properties of a class are understood as a variable in a class, then the constants and variables of the class are different and are defined by:
class test{
       Private $a;
      Const PI = ' 3.14 ';
      .....
     //Call the above constants in a class in two ways, "$this::P i", or "class name::P I", here is test::P I, as follows:
       function GetValue () {
            return $this->a * $this::P i; or $this->a * Test::P I, with the This keyword or class name, but with a double colon.
    }
}
$e = new test ();
$e->PI =5;  //Note that-> only creates a property that is also named Pi, rather than changing the value of the PI constant in the class.
Echo $e::P I//This is the constant that invokes the class. The
constants can only be invoked with a double colon::. and cannot change its value.
There are also two ways to invoke a class constant after instantiating it outside of a class. The method is:
$e::P i    or "test::P i", the common point is to use a colon, the difference is that the external cannot use the This keyword, only the instance name, but the class name::P i is generic.

Static member of Class (static property or static method):
If you need to create fields or methods that are shared by instances of all classes. You have to use static members. There are two characteristics:
1, the static member is a communist, it lets all instances of the class on the script invoke, but not by the class of a specific instance name invoked, but outside the class, unified use of "class name:: $ member name" method call. The internal of the class is called using the "self::$ member name" uniformly.
2. When each new instance is created, the static member begins the recalculation from the last value of the last created instance, rather than starting with the initial value in the class.
3. For static members defined with public, you can change the value of it externally. Private and so on is not good.
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; Changes the value of a static member because of a member of the public definition.
$c = new test ();
Echo Test::getv (); Return 9

Seven, the key word:
(i) This keyword: the internal reference class for the class itself. To access a property or method or constant, such as a $this-> property name or a method name. $this:: Constant name. This can also be used in subclasses of the class to refer to a property or method of its own.
(ii) Double colon "::" Keyword: used to invoke constants, static members.
(iii) SELF keyword: a static member is called in conjunction with a double colon within a class, such as self:: $staticVar., within a class, static members cannot be invoked with $this.
(iv) __tostring (): Use __tostring () in a class to convert a class to a string and print a class for a small purpose: 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 written as: Echo $a->__tostring ();
(v) __clone (): When cloning an object, this keyword is used to change certain values when cloning.
(vi) __call (): Method overload, the following example:
Class cb{
function __call ($method, $n) {
if ($method = = ' Showvartype ') {
if (is_numeric ($n [0])) {//$n cannot be used. To use $n[0];
$this->displaynum ();
}else if (Is_array ($n [0])) {
$this->displayarr ();
}else{
$this->displayother ();
}
}
}
function Displaynum () {
Echo ' }
function Displayarr () {
Echo ' }
function Displayother () {
Echo ' }
}

$x = ' a ';
$y =array (' A ', ' B ');
$b =new CB;
$b->showvartype ($x); Not an array, not 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.
(vii) extends: inheritance: such as Class a{} Class B extends a{} Class B inherits Class A


Attachment: Memory: Future unification with "->" when calling a method or property, a constant is invoked with a double colon "::", not dizzy.

Viii. scope of methods and properties:
A total of 6 kinds: public (default, can be omitted, also equivalent to the PHP6 var declaration), Private (private, also can not be used by subclasses), protected (private, but can be used by subclasses), abstract (abstract, context), final (block in the subclass to prevent overwriting- Also known as overloading, block is inherited, used to modify class names and methods, such as final class test{final function fun () {}}, but not for attributes), static (static)

IX: Abstract classes and abstract methods (abstract--Note: There is no abstract attribute):
An abstraction can be understood as a parent class that defines a template or base class for a subclass. Scope Abstract is declared only in the parent class, but is implemented in subclasses. Precautions:
1, abstract class can not be instantiated, can only quilt class (concrete Class) After the implementation of inheritance.
2. An abstract class must implement all the abstract methods of the abstract class in its subclasses. Otherwise there will be an error.
3, in the abstract method, just declare, but can not be implemented concretely: such as abstract function Gettow () {return $this->p;} Is wrong, you can only declare this method: Abstract function Gettow () (not even brackets {}), abstract methods and abstract classes are mainly used in complex class-level relationships. This hierarchical relationship needs to ensure that each subclass contains and overloads some specific methods. This can also be achieved through the interface
4, the attribute cannot be named abstract property, such as abstract $p = 5 is wrong.
5. Only classes declared as abstract can declare abstract methods, but they cannot be implemented if the method is declared abstract. Such as:
Abstract class Employee
{
Abstract function A (...);
Abstract function B (...);
}
Later, the parent class is extended to form a variety of subclasses such as managers, employees, and cashiers.
6, in the abstract class, if you want to implement a specific method, cannot be declared as abstract. That might actually be more meaningful. You can extract the common parts of several class libraries into an abstract class, and the other classes inherit the abstract class. As follows:
Abstract class baseshop{
Const tax=0.06; Defining constants in an abstract class
Public function Buy ($gid) {//If defined as an abstract method, the abstract function buy () cannot implement the body here.
Echo (' you purchased the product with ID: '. $gid. ');
}
Public function Sell ($gid) {
Echo (' You sold the product with ID: '. $gid. ');
}
Public Function View ($gid) {
Echo (' You look at the product with 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 (' }
}
$s = new Ballshop;
$s->open (); You sold a product with ID: 2314
$shop->gettax ();

Current 1/2 page 12 Next read the full text

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.