PASSWORD RESET

Your destination for complete Tech news

PHP

What is the difference between public, private and protected in PHP?

380 0
< 1 min read

In PHP, public, private, and protected are access modifiers that determine the visibility and accessibility of class members (properties and methods).

Here is a brief overview of the difference between public, private, and protected in PHP:

  • public: Class members marked as public can be accessed from anywhere, inside or outside the class. They can be accessed directly using the $object->member syntax, or through a method.
  • private: Class members marked as private can only be accessed from within the class. They cannot be accessed directly using the $object->member syntax, and cannot be inherited by child classes.
  • protected: Class members marked as protected can only be accessed from within the class and its child classes. They cannot be accessed directly using the $object->member syntax, but can be accessed through a method.

Here is an example of how to use public, private, and protected members in a PHP class:

<?php

class MyClass
{
    public $publicProperty = 'public';
    private $privateProperty = 'private';
    protected $protectedProperty = 'protected';

    public function getPrivateProperty()
    {
        return $this->privateProperty;
    }

    protected function getProtectedProperty()
    {
        return $this->protectedProperty;
    }
}

$object = new MyClass();

echo $object->publicProperty; // Outputs 'public'
echo $object->privateProperty; // Throws an error
echo $object->getPrivateProperty(); // Outputs 'private'
echo $object->protectedProperty; // Throws an error
echo $object->getProtectedProperty(); // Throws an error

In this example, the publicProperty can be accessed directly, while the privateProperty and protectedProperty can only be accessed through methods. The getPrivateProperty() method can be called from anywhere, while the getProtectedProperty() method can only be called from within the class or its child classes.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.