PHP Class Access Control Modifiers

Description

Access control modifiers can place before a class, a method definition, or a property to alter the way PHP treats them.

List of Access Control Modifiers

Access Modifiers Meaning
Public Set property or method to be accessible from anywhere
Private Set property or method to be accessible only by its own class or object
ProtectedSet property or method to be accessible by its class or by its descendants
Final Set property, method, or class cannot be overridden in subclasses
Abstract Set method or class cannot be used directly. We have to subclass it.

Most of the variables in a class should be marked as either protected or private.

Public

Public properties and methods are accessible from anywhere.


<?PHP// w ww.  j  a  v  a 2s. c  o  m
class Book {
        public $Name;
        public function say() {
                print "PHP!\n";
        }
}
class PythonBook extends Book {
        public function say() {
                print "Python!\n";
        }
}

$aBook = new PythonBook;
$aBook->Name = "Python";
print $aBook->Name;
?>

By default, all class methods are public.

The code above generates the following result.

Private

Private properties are accessible only inside its own the class.


<?PHP//from w  ww .  j a v  a2 s. c  o m
class Book {
        private $Name;
        private $NameTag;
        public function setName($NewName) {
                // etc
        }
}
?>

Child classes cannot access private parent methods and properties. If you want to do this, you need the protected keyword instead.

Protected

Protected properties and methods are accessible within its owns class and a child class. Consider the following code:


<?PHP/*  w w w  .  j  a  v a 2  s .  co  m*/
class Book {
        public $Name;
        protected function getName() {
                return $this->Name;
        }
}

class Poodle extends Book {
        public function say() {
                print "'Book', says " . $this->getName();
        }
}

$aBook = new Poodle;
$aBook->Name = "PHP";
$aBook->say();
?>

The code above generates the following result.





















Home »
  PHP Tutorial »
    Language Basic »




PHP Introduction
PHP Operators
PHP Statements
Variable
PHP Function Create
Exception
PHP Class Definition