PHP Class Access Control Modifiers

In this chapter you will learn:

  1. What are PHP Class Access Control Modifiers
  2. List of Access Control Modifiers
  3. Public
  4. Private
  5. Protected

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//  j a v a2s.co 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 jav  a  2 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/*from  j  av a  2s.c  o  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.

Next chapter...

What you will learn in the next chapter:

  1. What is a constructor
  2. Syntax to create a constructor
  3. Example - Class with a constructor
  4. Example - Constructor with arguments
  5. Example - Parent Constructors
Home » PHP Tutorial » PHP Class Definition
Concept for Object Oriented Design
PHP Class Definition
PHP Create Object from Class
PHP Class Properties
PHP Iterating Object Properties
PHP Class Inheritance
PHP Overriding Methods
PHP final Classes and Methods
PHP Abstract Class
PHP Class Access Control Modifiers
PHP Class Constructor
PHP Class Destructors
PHP Class Magic Methods