简体   繁体   English

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

[英]Protected and private visibility in php

I have been learning PHP from an online course. 我从在线课程学习PHP。 I have declared protected class members. 我已经宣布了受保护的类成员。 These members are not supposed to be accessible outside the class, but I'm able to access them. 这些成员不应该在课堂外访问,但我可以访问它们。

This is the class (class.Address.inc.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;

This is the Demo.php file in which I used the Address class. 这是我使用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";

I am able to access the protected member and initialize it from Demo.php. 我能够访问受保护的成员并从Demo.php初始化它。 Shouldn't protected members not be available outside the class from which it was declared? 受保护的成员不应该在宣布成员的课程之外吗?

Not sure but will try to take a little test again.... 不确定,但会尝试再次进行一点测试....

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

how to access protected vars outside class, here you can get its value same you can do for 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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM