Reputation: 778
I am new to PHP. I now learn the visibility scope concept (also known as access modifiers).
I read the following two links also on this forum:
Failed to get an object property that containing ":protected"
What is the difference between public, private, and protected?
I created a simple class in a file named "class.Address.inc":
<?php
/**
* Physical address.
*/
class Address {
// Street address.
public $street_address_1;
public $street_address_2;
// Name of the City.
public $city_name;
// Name of the subdivison.
public $subdivision_name;
// Postal code.
public $postal_code;
// Name of the Country.
public $country_name;
// Primary key of an Address.
protected $_address_id;
// When the record was created and last updated.
protected $_time_created;
protected $_time_updated;
/**
* Display an address in HTML.
* @return string
*/
function display() {
$output = '';
// Street address.
$output .= $this->street_address_1;
if ($this->street_address_2) {
$output .= '<br/>' . $this->street_address_2;
}
// City, Subdivision Postal.
$output .= '<br/>';
$output .= $this->city_name . ', ' . $this->subdivision_name;
$output .= ' ' . $this->postal_code;
// Country.
$output .= '<br/>';
$output .= $this->country_name;
return $output;
}
}
Then, I created a simple program in the file demo.php as follows:
require 'class.Address.inc';
echo '<h2>Instantiating Address</h2>';
$address = new Address;
echo '<h2>Empty Address</h2>';
echo '<tt><pre>' . var_export($address, TRUE) . '</pre></tt>';
echo '<h2>Setting properties...</h2>';
$address->street_address_1 = '555 Fake Street';
$address->city_name = 'Townsville';
$address->subdivision_name = 'State';
$address->postal_code = '12345';
$address->country_name = 'United States of America';
echo '<tt><pre>' . var_export($address, TRUE) . '</pre></tt>';
echo '<h2>Displaying address...</h2>';
echo $address->display();
echo '<h2>Testing protected access.</h2>';
echo "Address ID: {$address->_address_id}";
Everything works in the above program except of the last line. I am getting a fatal error saying I can`t access the "_address_id property". Why?
Protected scope is when you want to make your variable/function visible in all classes that extend current class including the parent class.
"$address" object comes from the current class named Address. So what am I doing wrong?
Please assist.
Qwerty
Upvotes: 0
Views: 3993
Reputation: 781004
The code that tries to access the protected property has to be in a method of the class or a class that extends it. The echo
line that you're asking about is not in any class method, it's in the global code of the script. Protected and private properties are not visible outside the class.
Upvotes: 4