为什么我不能直接从它自己的类访问受保护的属性


Why I can`t access a protected property from its own class directly?

我是PHP的新手。我现在学习可见性范围概念(也称为访问修饰符)。

我也在这个论坛上阅读了以下两个链接:

无法获取包含":p rotected"的对象属性

公共、私有和受保护之间有什么区别?

我在一个名为"class"的文件中创建了一个简单的类。地址.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;
  }
}

然后,我在文件演示中创建一个简单的程序.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 的当前类。那我做错了什么呢?

请协助。

键盘

尝试访问受保护属性的代码必须位于类的方法或扩展它的类中。您询问的echo行不在任何类方法中,而是在脚本的全局代码中。受保护属性和私有属性在类外部不可见。