Access control
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; The error attribute must define access control
var $speed = 10; Equivalent to Public
Public $name; Defining common attributes
}
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 {
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 methods can call private methods, 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
PHP access Control