Why can var_dump ascertain values of private variables, yet it can't when trying to access a single the property

柔情痞子 提交于 2019-11-30 23:29:40

That's the idea of private properties: You can't access them. You should really not break this concept. If you really want to access such property, mark is as "public" in the original class definition.

The reason why var_dump can access it is because it is an internal function, and it has the "power" to view the whole object. However, your code doesn't have that power.

I wouldn't recommend it, but if you really need to access a private property, you can use PHP Reflection to achieve it.

Private properties that are needed by external code usually have a public method to read them, in this case it's getItems().

$items = $_SESSION['PHPurchaseCart']->getItems();

I see that it's private, but I can't help but wonder why var_dump can show me what the property contains yet I can't read the data as it throws a fatal error?

Please understand you should use getter and setter methods as explained in the chosen answer.

But for completion on why and how it can be read (could help in debugging). Well, the value is there but private methods are surrounded by NULL bytes (ASCII Value 0).

So if you really want to see that value with a var_dump();

$key = "\0_items\0";
var_dump($fun->$key);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!