为什么可以通过引用从外部类访问私有变量? [英] Why is it possible to access private variables from outside class by reference?
问题描述
如果我有一个公共类方法正在返回对不可见(私有或受保护)属性的引用,则可以使用该引用来获得直接访问:
If I have a public class method that is returning a reference to a non-visible (private or protected) property, I can use that reference to gain direct access:
PHP代码
class A
{
private $property = 'orange';
public function &ExposeProperty()
{
return $this->property;
}
public function Output()
{
echo $this->property;
}
}
$obj = new A();
# prints 'orange'
$obj->Output();
$var = &$obj->ExposeProperty();
$var = 'apple';
# prints 'apple'
$obj->Output();
PHP中此功能的背后是否有原因?还是仅仅是设计监督,无法通过引用来跟踪访问冲突?
Is there a reasoning behind this functionality in PHP? Or is it just a design oversight, failing to keep track of access violations through references?
当您想要实现以下目标时,它显然很方便:
It obviously comes in handy when you want to achieve something like:
PHP代码
$this->load->resource();
其中load
是修改$this
的给定属性的对象.但是除了这个捷径之外,我看不到有很多可能的用途,否则使用有效的OOP模式是不可能的.
Where load
is an object that modifies given properties of $this
. But apart from this shortcut, I don't see many possible uses which wouldn't be possible with valid OOP patterns otherwise.
推荐答案
好吧,您正在显式返回对值的引用.您正在锁定前门,但随后将打开侧门.您正在故意瞄准并在这里射出自己的脚.如果$property
是一个对象,并且无论是否带有&
引用都将返回该对象,对该对象的任何修改也将反映在$property
上.这就是 reference 的工作方式,它总是修改该引用指向的唯一值.
Well, you are explicitly returning a reference to a value. You're locking the front door, but are then opening a side entrance. You are very deliberately taking aim and shooting your own foot here. If $property
was an object, and you'd return this object with or without &
reference, any modifications to this object would be reflected on $property
as well. That's how a reference works, it always modifies the one and only existing value that the reference points to.
可见性修饰符不是魔术般的铁皮保护".有多种方法可以绕过private
可见性来访问和修改属性.它们主要是作为您自己和其他开发人员的标志,该标志不应直接访问此属性,仅供内部使用,而不是公开认可的API.如果您愿意,PHP会让您耳目一新算了没什么,没什么.
Visibility modifiers aren't magic iron clad "protections". There are any number of ways how you can circumvent a private
visibility to access and modify the property. They're mostly there as a flag to yourself and other developers that this property should not be accessed directly, it's for internal use and not a publicly sanctioned API. And PHP will slap you on the wrist should you forget that. Nothing more, nothing less.
此外,这里没有任何侵犯.外部代码绝对不能访问或修改$obj->property
.这是private
唯一应禁止的事情.本质上,您是在对象上公开一个公共API,该公共API修改了private
属性.通常,这是通过getter和setter函数完成的,但是按引用的API显然也可以工作.
Also, nothing is really being violated here. Outside code is at no point accessing or modifying $obj->property
. That's the only thing private
is supposed to prohibit. You're essentially exposing a public API on your object which modifies a private
property. Usually this is done with getter and setter functions, but a by-reference API obviously works as well.
这篇关于为什么可以通过引用从外部类访问私有变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!