Home > Article > Backend Development > Detailed explanation of PHP classes and object-oriented
This article mainly shares with you the basic parts of PHP, detailed explanations of PHP classes and object-oriented, there are ten points in total, I hope it can help everyone.
1. PHP classes and objects
<?php//定义一个类class Car { var $name = '汽车'; function getName() { return $this->name; } }//实例化一个car对象$car = new Car();$car->name = '奥迪A6'; //设置对象的属性值echo $car->getName(); //调用对象的方法 输出对象的名字
3. Class attributes
The variables defined in the class are called attributes. Usually attributes are related to the fields in the database. association, so it can also be called a "field". A property declaration starts with the keywords public, protected or private, followed by an ordinary variable declaration. Attribute variables can be initialized with a default value, and the default value must be a constant.
The meaning of the access control keyword is:
public:公开的 protected:受保护的 private:私有的 class Car { //定义公共属性 public $name = '汽车'; //定义受保护的属性 protected $corlor = '白色'; //定义私有属性 private $price = '100000';} 默认都为public,外部可以访问。一般通过->对象操作符来访问对象的属性或者方法,对于静态属性则使用::双冒号进行访问。当在类成员方法内部调用的时候,可以使用$this伪变量调用当前对象的属性。 $car = new Car();echo $car->name; //调用对象的属性echo $car->color; //错误 受保护的属性不允许外部调用echo $car->price; //错误 私有属性不允许外部调用 受保护的属性与私有属性不允许外部调用,在类的成员方法内部是可以调用的。 class Car{ private $price = '1000'; public function getPrice() { return $this->price; //内部访问私有属性 }}
4. Class methods
Methods are functions in the class. Many times we cannot distinguish between methods and What is the difference between functions? In process-oriented programming, function is called a function, while in object-oriented programming, function is called a method.
Like attributes, class methods also have public, protected and private access control.
The meaning of the access control keywords is:
public: public
protected: protected
private: private
We can define the method like this
class Car { public function getName() { return '汽车'; }}$car = new Car();echo $car->getName(); 使用关键字static修饰的,称之为静态方法,静态方法不需要实例化对象,可以通过类名直接调用,操作符为双冒号::。 class Car { public static function getName() { return '汽车'; }}echo Car::getName(); //结果为“汽车”
5. Constructor and destructor
PHP5可以在类中使用__construct()定义一个构造函数,具有构造函数的类,会在每次对象创建的时候调用该函数,因此常用来在对象创建的时候进行一些初始化工作。 class Car { function __construct() { print "构造函数被调用\n"; }}$car = new Car(); //实例化的时候 会自动调用构造函数__construct,这里会输出一个字符串 在子类中如果定义了__construct则不会调用父类的__construct,如果需要同时调用父类的构造函数,需要使用parent::__construct()显式的调用。 class Car { function __construct() { print "父类构造函数被调用\n"; }}class Truck extends Car { function __construct() { print "子类构造函数被调用\n"; parent::__construct(); }}$car = new Truck(); 同样,PHP5支持析构函数,使用__destruct()进行定义,析构函数指的是当某个对象的所有引用被删除,或者对象被显式的销毁时会执行的函数。 class Car { function __construct() { print "构造函数被调用 \n"; } function __destruct() { print "析构函数被调用 \n"; }}$car = new Car(); //实例化时会调用构造函数echo '使用后,准备销毁car对象 \n';unset($car); //销毁时会调用析构函数
When the PHP code is executed, the object will be automatically recycled and destroyed, so under normal circumstances there is no need to explicitly destroy the object.
6. Static keyword
Static properties and methods can be called without instantiating the class, and can be called directly using the class name::method name. Static properties do not allow objects to be called using the -> operator.
class Car { private static $speed = 10; public static function getSpeed() { return self::$speed; }}echo Car::getSpeed(); //调用静态方法 静态方法也可以通过变量来进行动态调用 $func = 'getSpeed';$className = 'Car';echo $className::$func(); //动态调用静态方法
In static methods, the $this pseudo variable is not allowed to be used. You can use self, parent, static to call static methods and properties internally.
class Car { private static $speed = 10; 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();
7. Access control
In the previous section, we have already touched on access control. Access control is implemented through the keywords public, protected and private. Class members defined as public can be accessed from anywhere. A class member defined as protected can be accessed by itself, its subclasses, and its parent class. Class members defined as private can only be accessed by the class in which they are defined.
Class attributes must be defined as one of public, protected, and private. For compatibility with versions prior to PHP5, if defined using var, it is considered public.
class Car { $speed = 10; //错误 属性必须定义访问控制 public $name; //定义共有属性} 类中的方法可以被定义为公有、私有或受保护。如果没有设置这些关键字,则该方法默认为公有 class Car { //默认为共有方法 function turnLeft() { } } 如果构造函数定义成了私有方法,则不允许直接实例化对象了,这时候一般通过静态方法进行实例化,在设计模式中会经常使用这样的方法来控制对象的创建,比如单例模式只允许有一个全局唯一的对象。 class Car { private function __construct() { echo 'object create'; } private static $_object = null; public static function getInstance() { if (empty(self::$_object)) { self::$_object = new Car(); //内部方法可以调用私有方法,因此这里可以创建对象 } return self::$_object; } }//$car = new Car(); //这里不允许直接实例化对象$car = Car::getInstance(); //通过静态方法来获得一个实例
8. Object Inheritance
Inheritance is a commonly used feature in object-oriented programming. Car is a relatively large class. We can also call it a base class. In addition Cars are also divided into trucks, cars, Dongfeng, BMW, etc. Because these subclasses have many of the same attributes and methods, you can inherit the car class to share these attributes and methods to achieve code reuse.
class Car { public $speed = 0; //汽车的起始速度是0 public function speedUp() { $this->speed += 10; return $this->speed; } }//定义继承于Car的Truck类class Truck extends Car{ public function speedUp(){ $this->speed = parent::speedUp() + 50; } }
9. Overloading
Overloading in PHP refers to the dynamic creation of properties and methods, which is achieved through magic methods. The overloading of attributes uses __set, __get, __isset, and __unset to implement assignment, reading, determining whether the attribute is set, and destroying the attribute if it does not exist, respectively.
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 = '汽车'; //name属性动态创建并赋值echo $car->name; 方法的重载通过__call来实现,当调用不存在的方法的时候,将会转为参数调用__call方法,当调用不存在的静态方法时会使用__callStatic重载。 class Car { public $speed = 0; public function __call($name, $args) { if ($name == 'speedUp') { $this->speed += 10; } } }$car = new Car();$car->speedUp(); //调用不存在的方法会使用重载echo $car->speed;
10. Advanced characteristics of objects Object comparison, when all attributes of two instances of the same class are equal, you can use the comparison operator == to judge. When you need to judge whether two variables are references to the same object, you can use the congruence operator = == Make a judgment.
class Car {}$a = new Car();$b = new Car();if ($a == $b) echo '=='; //trueif ($a === $b) echo '==='; //false 对象复制,在一些特殊情况下,可以通过关键字clone来复制一个对象,这时__clone方法会被调用,通过这个魔术方法来设置属性的值。 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); 对象序列化,可以通过serialize方法将对象序列化为字符串,用于存储或者传递数据,然后在需要的时候通过unserialize将字符串反序列化成对象进行使用 class Car { public $name = 'car'; }$a = new Car();$str = serialize($a); //对象序列化成字符串echo $str.' ';$b = unserialize($str); //反序列化为对象var_dump($b);
Related recommendations:
Auto-loading implementation method of PHP class
Detailed explanation of the dependency injection process of reflection implementation of PHP class
Principles of PHP class automatic loading and PHP chain operation
The above is the detailed content of Detailed explanation of PHP classes and object-oriented. For more information, please follow other related articles on the PHP Chinese website!