PHP classes and object-oriented explanations

Source: Internet
Author: User
Tags access properties object serialization php class

This article mainly share with you the basic part of PHP, PHP class and object-oriented detailed, a total of 10 points, I hope to help the degree to everyone.

First, PHP classes and objects

<?php//defines a class of car {    var $name = ' car ';    function GetName () {        return $this->name;    }} Instantiate a Car object $car = new car (); $car->name = ' Audi A6 '; Sets the property value of an object echo $car->getname ();  The name of the method output object that called the object

Iii. properties of a class

Variables defined in a class are called properties, and usually properties are associated with fields in the database, so they can also be called fields. A property declaration is made up of the keyword public,protected or private, followed by a common variable declaration. A variable of the property can be set to the default value of the initialization, and the default value must be constant.

The keyword for access control represents the meaning:

Public: Publicly available protected: Protected Private: Private class Car {    //define public property publicly    $name = ' car ';    Defines the protected property    protected $corlor = ' white ';     Define private Property    $price = ' 100000 ';} The default is public, and external access is available. Object operators typically access properties or methods of an object, and for static properties use:: Double colons for access. When called inside a class member method, you can use the $this pseudo-variable to invoke the properties of the current object. $car = new car (); Echo $car->name;   Invoking the properties of an object echo $car->color;  Incorrectly protected properties do not allow external calls to echo $car->price;  The error private property does not allow external calls to protected properties with private properties that do not allow external calls, which can be called inside a member method of a class. Class car{    Private $price = ' + ';    Public Function GetPrice () {        return $this->price;//Internal Access private property    }}

Iv. methods of the class

method is the function in the class, many times we can not tell the difference between the method and the function, in the process-oriented program design is called functions, in object-oriented function is called a method.

Like properties, the methods of the class also have public,protected and private access control.

The keyword for access control represents the meaning:
Public: Publicly available
Protected: Protected
Private: Private

We can define methods like this

Class Car {public    function GetName () {        return ' car ';    }} $car = new car (); Echo $car->getname (); static methods, called static methods with the keyword static, do not need to instantiate the object, can be called directly through the class name, the operator is a double colon:. Class Car {public    static function GetName () {        return ' car ';    }} Echo Car::getname (); The result is "car"

Five, constructors and destructors

PHP5 can use __construct () in a class to define a constructor, a class with constructors that will call the function every time the object is created, so it is often used to do some initialization work when the object is created. Class Car {   function __construct () {       print "constructor is called \ n";   }} $car = new car (); The constructor __construct is automatically invoked when instantiated, where a string is output, and if __construct is defined in the subclass, the __construct of the parent class is not called, and if the constructor of the parent class needs to be called at the same time, you need to use parent::__ Construct () an explicit call. Class Car {   function __construct () {       print "parent class constructor is called \ n";   }} Class Truck extends Car {   function __construct () {       print "subclass constructor is called \ n";       Parent::__construct ();   }} $car = new Truck (); Similarly, PHP5 supports destructors, which are defined using __destruct (), which refers to functions that are executed when all references to an object are deleted, or when an object is explicitly destroyed. Class Car {   function __construct () {       print "constructor is called \ n";   }   function __destruct () {       print "destructor is called \ n";   }} $car = new car (); When instantiated, the constructor is called after Echo ' is used, ready to destroy the car object \ n '; unset ($car); Destructors are called when destroying

When the PHP code is executed, the object is automatically reclaimed and destroyed, so it is generally not necessary to destroy the object explicitly.

Vi. Static Keywords

Static properties and methods can be called without instantiating a class, directly using the class Name:: Method name. Static properties do not allow an object to be called with an operator.

Class Car {    private static $speed = ten;    public static function GetSpeed () {        return self:: $speed;    }} Echo Car::getspeed ();  Calling static methods static methods can also be dynamically called by variables $func = ' getspeed '; $className = ' Car '; Echo $className:: $func ();  Dynamic invocation of static methods

In a static method, $this pseudo-variable is not allowed. You can use Self,parent,static to invoke static methods and properties internally.

Class Car {    private static $speed = ten;    public static function GetSpeed () {        return self:: $speed;    }    public static function SpeedUp () {        return self:: $speed +=10;    }} Class Bigcar extends Car {public    static function start () {        parent::speedup ();}    } Bigcar::start (); Echo Bigcar::getspeed ();

Vii. access Control

In the previous section, we have been exposed to access control, and access control is implemented by keyword public,protected and private. Class members that are defined as public can be accessed from anywhere. A class member that is defined as protected can be accessed by itself and its subclasses and parent classes. A class member that is defined as private can only be accessed by the class in which it is defined.

Class properties must be defined as public, protected, and private. To be compatible with previous versions of PHP5, if the VAR definition is used, it is considered public.

Class Car {   $speed = 10;//Error attribute must define access control public   $name;   Methods in defining a common property} class can be defined as public, private, or protected. If these keywords are not set, the method defaults to public class Car {   //default to Common method   function TurnLeft () {   }} if the constructor is defined as a private method, the object is not allowed to be instantiated directly. This is typically done by static methods, which are often used in design mode to control the creation of objects, such as a singleton pattern that only allows a globally unique object. Class Car {   private function __construct () {       echo ' object create ';   }    private static $_object = null;    public static function getinstance () {       if (empty (Self::$_object)) {            self::$_object = new Car ();//internal method can call private method , so you can create objects here       }        return self::$_object;}   } $car = new car (); Direct instantiation of objects is not allowed here $car = Car::getinstance (); Using static methods to obtain an instance

Viii. Object Inheritance

Inheritance is a common feature in object-oriented programming, the car is a relatively large class, we can also call it the base class, in addition, the car is divided into trucks, cars, Dongfeng, BMW, etc., because these subclasses have many of the same properties and methods, can inherit the car class to share these properties and methods, Implement code reuse.

Class Car {public    $speed = 0;//The starting speed of the car is 0 public    function speedUp () {        $this->speed + = ten;        return $this->speed;    }} Define Truck class Truck extends car{public    function SpeedUp () {        $this->speed = parent::speedup () + 50;<, which is inherited from Car c7/>}}

Nine, heavy

Overloading in PHP refers to the dynamic creation of properties and methods, which are implemented by magic methods. The overloads of a property are implemented by __set,__get,__isset,__unset to assign, read, and determine whether a property is set or destroyed, respectively, for a nonexistent property.

Class Car {   private $ary = Array ();    Public Function __set ($key, $val) {       $this->ary[$key] = $val;   }    Public Function __get ($key) {       if (isset ($this->ary[$key]) {            return $this->ary[$key];       }        return null;   }    Public Function __isset ($key) {       if (isset ($this->ary[$key])) {            return true;       }        return false;   }    Public Function __unset ($key) {       unset ($this->ary[$key]);}   } $car = new Car (); $car->name = ' car ';  The Name property dynamically creates and assigns a value to echo $car the overload of the->name; method is implemented by __call, and when a non-existent method is called, the __call method is called, and the __callstatic overload is used when a static method that does not exist is called. Class Car {public   $speed = 0;    Public Function __call ($name, $args) {       if ($name = = ' SpeedUp ') {            $this->speed + =       ;   }} $car = new Car (); $car->speedup (); Calling a method that does not exist uses the overload echo $car->speed;

The advanced Attribute object comparison of the object, when all properties of the same class of two instances are equal, can be judged by using the comparison operator = =, when it is necessary to determine whether two variables are references of the same object, you can use the congruent operator = = = to judge.

class car {} $a = new car (), $b = new Car (), if ($a = = $b) echo ' = = '; Trueif ($a = = = $b) echo ' = = = '; False object replication, in some special cases, you can copy an object through the keyword clone, then the __clone method is called, this magic method to set the value of the property.    Class Car {public $name = ' car ';        Public Function __clone () {$obj = new Car ();   $obj->name = $this->name; }} $a = new car (), $a->name = ' new car '; $b = clone $a; var_dump ($b); object serialization, which can be serialized as a string by serialize method for storing or passing data. Then use class Car {public $name = ' car ' when necessary by deserializing the string into an object by Unserialize) $a = new Car (); $str = serialize ($a); The object is serialized into a string echo $str. "; $b = Unserialize ($STR); Deserializes to Object Var_dump ($b); 
Related Article

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.