PHP access Control

Source: Internet
Author: User

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

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.