PHP Public Protected Private attribute instance detailed

Source: Internet
Author: User
Tags php class

There are three properties for functions and class variables in the PHP class: Public protected private, when to use what attributes are good entanglements, deliberately found an instance, so that looks clearer.

Public represents the global, and the inner and outer subclasses of the class can be accessed;
Private means that only this class can be used internally;
Protected is protected and is accessible only in this class or subclass or in the parent class;

<?php
Parent class
Class father{
Public function A () {
echo "function a";
}
Private Function B () {
echo "function B";
}
protected function C () {
echo "Function C";
}
}
Sub-class
Class Child extends father{
Function d () {
Parent::a ();//Call the parent Class A method
}
function e () {
Parent::c (); Call the C method of the parent class
}
function f () {
Parent::b (); Call the B method of the parent class
}

}
$father =new father ();
$father->a ();
$father->b (); Show error external cannot call private method called to protected method Father::b ()
$father->c (); Display error external cannot invoke protected method call to Private method Father::c ()

$chlid =new Child ();
$chlid->d ();
$chlid->e ();
$chlid->f ();//Display error cannot invoke parent class private method call to Private method Father::b ()
?>

done!

PHP Public Protected Private attribute instance detailed

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.