简体   繁体   English

PHP 如何在内部访问属性?

[英]How does PHP access properties internally?

Following up on this documentation: https://www.php.net/manual/en/language.oop5.references.php跟进本文档: https://www.php.net/manual/en/language.oop5.references.php

One of the key-points of PHP OOP that is often mentioned is that "objects are passed by references by default". PHP OOP 的重点之一就是“对象默认通过引用传递”。 This is not completely true.这并不完全正确。

In PHP, an object variable doesn't contain the object itself as value.在 PHP 中,object 变量不包含 object 本身作为值。 It only contains an object identifier which allows object accessors to find the actual object.它只包含一个 object 标识符,它允许 object 访问器找到实际的 object。

How does this actually work?这实际上是如何工作的? In C++ for example it seems that the arrow operator implicitly dereferences the pointer and then accesses the properties like when accessing them on the object variable itself.例如,在 C++ 中,箭头运算符似乎隐式地取消引用指针,然后访问属性,就像在 object 变量本身上访问它们时一样。

Here's what I mean:这就是我的意思:

obj->prop
(*obj).prop // equivalent to line above

This seems pretty clean.这看起来很干净。 The property is called as the sum of the object-variable-address and the property-offset in both cases.在这两种情况下,该属性都称为对象变量地址和属性偏移量的总和。

But how does that work in PHP?但这在 PHP 中是如何工作的? The documentation suggests that the pointer does not store the memory address but rather an "object-identifier".文档建议指针不存储 memory 地址,而是存储“对象标识符”。 Is accessing properties in PHP a highly abstracted process or does it resolve the object-identifier for the memory address and then access it in a similar way to C++ / Java / etc.? Is accessing properties in PHP a highly abstracted process or does it resolve the object-identifier for the memory address and then access it in a similar way to C++ / Java / etc.?

It's a highly abstracted process, similarity in syntax does not indicate that the code "falls through" to working like C/C++.这是一个高度抽象的过程,语法上的相似性并不表示代码“失败”到像 C/C++ 一样工作。 You can dive into the code to see how it works under the covers.您可以深入研究代码以了解它在幕后是如何工作的。

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

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