Php 为什么派生类访问基类私有属性?
我不明白这个话题。为什么基类的私有成员由派生类访问Php 为什么派生类访问基类私有属性?,php,Php,我不明白这个话题。为什么基类的私有成员由派生类访问 <?php class A{ private $name; // private variable private $age; //private variable } class B extends A{ public function Display($name,$age){ echo $this->name=$name." age is ".$this->age=$age; } } $ob=new B();
<?php
class A{
private $name; // private variable
private $age; //private variable
}
class B extends A{
public function Display($name,$age){
echo $this->name=$name." age is ".$this->age=$age;
}
}
$ob=new B();
$ob->Display("xyz",23);
?>
输出:
xyz age是23类
B
不继承$name
和$age
属性,因为它们是私有的
但是,PHP允许您分配变量,而无需首先将其声明为类属性:
<?php
class A
{
private $name; // private variable
private $age; //private variable
public function __construct()
{
$this->name = "a";
}
}
class B extends A
{
public function display($name, $age) {
$this->name2 = $name; // new name2 variable, NOT A's name
$this->age2 = $age; // new age2 variable, NOT A's age
echo $this->name2." age is ".$this->age2.PHP_EOL;
echo $this->name; // A's name, undefined property warning!
}
}
$ob=new B();
$ob->display("xyz", 23);
您只需将变量设置为受保护
而不是私有