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; Define Common Properties}
A method in a class can be defined as public, private, or protected. If these keywords are not set, the method defaults to public.
Class Car {? The default is common method function TurnLeft () { }}
If the constructor is defined as a private method, it is not allowed to instantiate the object directly, which is typically instantiated by a static method, which is 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
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
PHP access Control