php OOP Access specifiers - public, protected private etc

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
finchamgroves
Forum Newbie
Posts: 11
Joined: Wed Oct 07, 2009 10:02 am

php OOP Access specifiers - public, protected private etc

Post by finchamgroves »

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.

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";
?>
 
 
jmaker
Forum Newbie
Posts: 16
Joined: Tue May 21, 2002 11:13 pm

Re: php OOP Access specifiers - public, protected private etc

Post by jmaker »

Visibility applies to the methods as well. You can't access a protected method outside of the class.
http://www.php.net/manual/en/language.o ... bility.php

Bad

Code: Select all

 
class Customer {
 
protected function getPhone() {
  // do something
}
 
}
$c = new Customer();
$c->getPhone();  // should fail
 
Good

Code: Select all

 
class Customer {
 
protected function getPhone() {
  // do something
}
 
function foo() {
  $this->getPhone();
}
 
}
$c = new Customer();
$c->foo();  // should work
 
ceiroa
Forum Newbie
Posts: 11
Joined: Thu Oct 08, 2009 4:14 pm

Re: php OOP Access specifiers - public, protected private etc

Post by ceiroa »

Protected methods can be accessed only from inside the same class AND classes that inherit from it. classChild can access a protected method of classParent if classChild extends classParent.

The purpose of the private modifier is to hide elements from the outside. A private method will be used only by other methods (private or public) in the same class. You can think of them as auxiliary methods to other methods in that class. For example, if a public method is too long you can break it down in a few methods, only one of them being public, lets call it X. All other methods will just make sense if they are called from X.

Carlos R. M. Eiroa
Last edited by onion2k on Fri Oct 09, 2009 8:29 am, edited 1 time in total.
Reason: Spam link deleted.
finchamgroves
Forum Newbie
Posts: 11
Joined: Wed Oct 07, 2009 10:02 am

Re: php OOP Access specifiers - public, protected private etc

Post by finchamgroves »

I've clearly totally got ther wrong end of the stick!
1. I created the class Customer.
2. I created a new instance of this class ($c)
3. So - if I call a variable or a function from within this new instance I expect this to be of the class Customer and therefore to be available even if protected or private.
4. From the outputs the variables (properties) are available in $c whether public, private or protected - at least when accessed by methods within the class.
5. From the output the functions (methods) only work in $c if they are specified as public. i.e. If I change the get_Salary function to protected it no longer works even in $c which is an instance of the same class - so the assumptions in paragraph (3) are obviously up the spout - but why?
6. Put another way - If I can't access a protected function from within an instance of the same class - then how can I access it? OK I can create another public function within the class (as per the first reply)to access the protected function but what's the point of making the first function protected and then adding a public function from which you can access that? In short - what's the point of a protected function if you have to access it via a public function?
Mark Baker
Forum Regular
Posts: 710
Joined: Thu Oct 30, 2008 6:24 pm

Re: php OOP Access specifiers - public, protected private etc

Post by Mark Baker »

finchamgroves wrote:3. So - if I call a variable or a function from within this new instance I expect this to be of the class Customer and therefore to be available even if protected or private.
private and protected methods and attributes/properties are only available from within the class: public methods and attributes/properties are available from within the class, and to external code.
finchamgroves wrote:4. From the outputs the variables (properties) are available in $c whether public, private or protected - at least when accessed by methods within the class.
Correct, they're available from within the class instance itself using $this, but their direct availability to external access is determined by their "visibility"

Accessing attributes from within the class

Code: Select all

 
public function displayAll() {
   echo $this->name;  // echoes the value of the name attribute
   echo $this->phone; // echoes the value of the phone attribute
   echo $this->salary; // echoes the value of the salary attribute
}
 
Accessing attributes from outside the class

Code: Select all

 
$c = new Customer();
 
echo $c->name;  // echoes the value of the name attribute because it's public
echo $c->phone; // generates an error because it's protected
echo $c->salary; // generates an error because it's private
 
finchamgroves wrote:5. From the output the functions (methods) only work in $c if they are specified as public. i.e. If I change the get_Salary function to protected it no longer works even in $c which is an instance of the same class - so the assumptions in paragraph (3) are obviously up the spout - but why?
Not correct. The same rules of "visibility" that apply to attributes/properties also apply to methods. If a method is defined as public, it can be called from outside the class. If it's private or protected, then it can only be called from another method within the same class instance as jmaker'sexample demonstrates.
finchamgroves wrote:6. Put another way - If I can't access a protected function from within an instance of the same class - then how can I access it? OK I can create another public function within the class (as per the first reply)to access the protected function but what's the point of making the first function protected and then adding a public function from which you can access that? In short - what's the point of a protected function if you have to access it via a public function?
The value of private or protected functions isn't in simple getters or setters, it's in protecting the internals of the class from external manipulation.

Code: Select all

 
class Customer
{ 
// declare variables
    public $name;
    private $salary;
 
//Setters and getters
//name
   private function checkPrivilege() {
      if ($_SESSION['HR_USER']) {
         return true;
      }
      return false;
   }
 
    public function setName($name) {
        $this->name = $name;
   }
    public function getName() {
        return $this->name;
   }
//salary
    public function setSalary($salary) {
        if ($this->checkPrivilege()) {
           $this->salary = $salary;
        } else {
           throw new Exception('Security Violation.');
        }
   }
    public function getSalary() {
        if ($this->checkPrivilege()) {
           return $this->salary;
        } else {
           throw new Exception('Security Violation.');
        }
   }
}
 
The checkPrivilege() method is private, so $c->checkPrivilege() is not accessible because the calling application should not need to access it. It's only relevant when testing whether the user has privilege when they try to access the public methods that call it
finchamgroves
Forum Newbie
Posts: 11
Joined: Wed Oct 07, 2009 10:02 am

Re: php OOP Access specifiers - public, protected private etc

Post by finchamgroves »

:D :D
Brilliant!
I've been agonizing over all this for nothing! :banghead:
Many thanks for your patience, forbearance and generosity of time.
John
Post Reply