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

时间:2014-12-29 11:36:00

标签: php visibility

我是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}";

除了最后一行之外,所有内容都适用于上述程序。我收到一个致命错误,说我无法访问&#34; _address_id属性&#34;。为什么呢?

受保护的范围是指您希望在扩展当前类(包括父类)的所有类中显示变量/函数。

&#34; $地址&#34; object来自当前名为Address的类。那么我做错了什么?

请协助。

的Qwerty

1 个答案:

答案 0 :(得分:3)

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