Public Private Protected variable concepts

private – can be accessed from WITHIN the class only

protected – can be accessed from WITHIN the class and INHERITING classes

public – can be accessed from code OUTSIDE the class as well

<?php
/**
* Define MyClass
*/
class MyClass
{
public $public = 'Public';
protected $protected = 'Protected';
private $private = 'Private';

function printHello()
{
echo $this->public;
echo ‘<br>’;
echo $this->protected;
echo ‘<br>’;
echo $this->private;
echo ‘<br>’;
}
}

//$obj = new MyClass();
//echo $obj->public; // Works
//echo $obj->protected; // Fatal Error
//echo $obj->private; // Fatal Error
//$obj->printHello(); // Shows Public, Protected and Private

/**
* Define MyClass2
*/
class MyClass2 extends MyClass
{
// We can redeclare the public and protected method, but not private
protected $protected = ‘Protected2’;

function printHello2()
{
echo $this->public;
echo ‘<br>’;
echo $this->protected;
echo ‘<br>’;
echo $this->private;
echo ‘<br>’;
}
}

$obj2 = new MyClass2();
//echo $obj2->public; // Works
//echo $obj2->private; // Undefined
//echo $obj2->protected; // Works
$obj2->printHello2(); // Shows Public, Protected2, Undefined

?>

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s