【问题标题】:Why I can`t access a protected property from its own class directly?为什么我不能直接从它自己的类中访问受保护的属性?
【发布时间】: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


【解决方案1】:

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

【讨论】:

  • 您好,感谢您的意见。课外可以公开吗?我可以在“公共”属性上使用 PHP 内置的 echo() 方法吗?
  • 是的。公共属性可以从任何地方访问,私有属性只能在类内部访问,在类及其子类中受到保护。
猜你喜欢
  • 1970-01-01
  • 2011-10-06
  • 1970-01-01
  • 2015-06-09
  • 2016-05-25
  • 2013-03-05
  • 2017-10-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多