php OOP Access specifiers - public, protected private etc
Posted: Thu Oct 08, 2009 10:08 am
I'm having a real problem getting my head around this.
E.g. In the code that follows I create a class and then create an instance of it.
The properties (variables) seem available from the instance whether public, private or protected (which I would expect).
The methods (functions) are only available when specified as public. If I change (say) the getPhone function to protected then it throws up a Fatal error: Call to protected method Customer::getPhone() from context - even in an instance of the same object - which I didn't expect.
Have been stuck on this for 2 days!!! Any advice hugely appreciated.
E.g. In the code that follows I create a class and then create an instance of it.
The properties (variables) seem available from the instance whether public, private or protected (which I would expect).
The methods (functions) are only available when specified as public. If I change (say) the getPhone function to protected then it throws up a Fatal error: Call to protected method Customer::getPhone() from context - even in an instance of the same object - which I didn't expect.
Have been stuck on this for 2 days!!! Any advice hugely appreciated.
Code: Select all
<?php
ini_set(error_reporting, E_ALL & ~E_NOTICE);
ini_set('display_errors',1);
class Customer
{
// declare variables
public $name;
protected $phone;
private $salary;
//Setters and getters
//name
public function setName($name)
{
$this->name = $name;
}
public function getName()
{
return $this->name;
}
//phone
public function setPhone($phone)
{
$this->phone = $phone;
}
public function getPhone()
{
return $this->phone;
}
//salary
public function setSalary($salary)
{
$this->salary = $salary;
}
public function getSalary()
{
return $this->salary;
}
}
//New instance
$c = new Customer();
$c->setName("Joseph Bloggs");
$c->setPhone("555457");
$c->setSalary("£12000");
//Get data
echo $c->getName();
echo"<br />\n";
echo $c->getPhone();
echo"<br />\n";
echo $c->getSalary();
echo"<br />\n";
?>