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


Protected and private visibility in php

我一直在从在线课程中学习PHP。我已经声明了受保护的类成员。这些成员不应该在类外访问,但我能够访问它们。

这是类(类。地址.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 初始化它。受保护的成员不应该在声明它的类之外不可用吗?

不确定,

但会尝试再次进行一些测试....

<?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";

如何在类外访问受保护的 var,在这里您可以获得与 set value 相同的值。

<?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();