【发布时间】:2015-02-25 14:14:57
【问题描述】:
我是 PHP 新手。我现在学习可见性范围概念(也称为访问修饰符)。
我也在这个论坛上阅读了以下两个链接:
Failed to get an object property that containing ":protected"
What is the difference between public, private, and protected?
我在名为“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;
}
}
然后,我在文件demo.php中创建了一个简单的程序如下:
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}";
除了最后一行之外,上述程序中的一切都有效。我收到一个致命错误,说我无法访问“_address_id 属性”。为什么?
受保护的范围是当您想让您的变量/函数在所有扩展当前类(包括父类)的类中可见时。
"$address" 对象来自当前名为 Address 的类。那我做错了什么?
请帮忙。
Qwerty
【问题讨论】:
-
echo行不在任何类函数中,它只是在脚本的顶层。 -
protected属性的要点是,除了从该实例内部或扩展该类的任何类的实例之外,它们无法被访问......您正试图从外部访问它实例
标签: php visibility