php中的受保护和私有可见性

时间:2016-07-11 09:37:49

标签: php

我从在线课程学习PHP。我已经宣布了受保护的类成员。这些成员不应该在课外访问,但我可以访问它们。

这是类(class.Address.inc.php)

Class Address
 {
     //Street Address
     protected $street_Address_1;
     public $street_Address_2;

     //Name of the city
     public $city_name;

     //Subdivision name
     public $subdivision_name;

     //Postal code
     public $postal_code;

     //country name
     public $country_name;

这是我使用Address类的Demo.php文件。

<?php

require 'class.Address.inc';

     $address=new Address;
     $address->street_Address_1= "555 Fake Street";//protected but accessible
     $address->street_Address_2="Hello";
     $address->city_name="Townsville";

我可以访问受保护的成员并从Demo.php初始化它。受保护的成员不应该在宣布成员的类别之外可用吗?

2 个答案:

答案 0 :(得分:0)

不确定,但会尝试再次进行一点测试......

<?php

require 'class.Address.inc'; //require 'class.Address.inc.php';
$address=new Address;
$address->street_Address_1= "555 Fake Street";//protected but accessible
$address->street_Address_2="Hello";
$address->city_name="Townsville";

答案 1 :(得分:0)

如何访问类外的受保护变量,这里可以获得与设置值相同的值。

<?php
class myclass{
    protected $myname;
    public function __construct(){
        $this->myname = "myclass class";
    }
}

class childclass extends myclass{

    public function __construct(){
        parent::__construct();
    }

    public function getMyName(){
        return $this->myname;
    }
}

$obj = new childclass();
echo $obj->getMyName();