PHP Visibility
Property visibility
property visibility defines the accessibility of property, Like which should property should be accessed only inside of class and which property should access both inside & outside of class.
These properties define as public, private & protected. If declared using var, the property will be defined as public.
How to declare property visibility
<?php
class MyClass
{
public $public = 'Public'; // This variable can be access anywhere
protected $protected = 'Protected'; // This variable can be access only inside of class
private $private = 'Private'; // This variable can be access only inside of class
function printHello()
{
echo $this->public;
echo $this->protected;
echo $this->private;
}
}
$obj = new MyClass();
echo $obj->public; // Works
echo $obj->protected; // It will give fatal error
echo $obj->private; // It will give fatal error
$obj->printHello(); // Shows Public, Protected and Private
?>
How to declare method visibility
PHP also supports the visibility concept of class methods, It declares by visibility keywords the same as property declaration.
If you did not use any visibility keyword then the method’s default visibility goes to public visibility.
<?php
class MyClass
{
// Declare a public constructor
public function __construct() { }
// Declare a public method
public function MyPublic() { }
// Declare a protected method
protected function MyProtected() { }
// Declare a private method
private function MyPrivate() { }
// This is public
function Foo()
{
$this->MyPublic();
$this->MyProtected();
$this->MyPrivate();
}
}
$myclass = new MyClass;
$myclass->MyPublic(); // Works
$myclass->MyProtected(); // Fatal Error
$myclass->MyPrivate(); // Fatal Error
$myclass->Foo(); // Public, Protected and Private work
?>
How to declare constant visibility
In PHP version >= 7.1.0 supports class constant’s visibility. This constant can be declared as public, private & protected. If you’re not using any visibility keyword to declare constant It will declare as public constant.
<?php
class MyClass
{
// Declare a public constant
public const MY_PUBLIC = 'public';
// Declare a protected constant
protected const MY_PROTECTED = 'protected';
// Declare a private constant
private const MY_PRIVATE = 'private';
public function foo()
{
echo self::MY_PUBLIC;
echo self::MY_PROTECTED;
echo self::MY_PRIVATE;
}
}
$myclass = new MyClass();
MyClass::MY_PUBLIC; // Works
MyClass::MY_PROTECTED; // Fatal Error
MyClass::MY_PRIVATE; // Fatal Error
$myclass->foo(); // Public, Protected and Private work
?>