Why php adds null bytes to private and protected property names?

▼魔方 西西 提交于 2020-01-04 06:18:21

问题


I am new to PHP world and learning it from php.net. I know that when casting object to an array then the null byte is added around the private and protected property names when ClassName or asterisk key (*) is prepended to the private and protected property names in the array keys.

But my question is that WHY php add null bytes WHAT is the reason ?

Can anyone tell in simple and easy words.

Examples will help a lot.

Thanks


回答1:


The point of private/protected properties is that you're not supposed to access them from outside the class itself. This is not a security measure or anything like that, it's to enforce contracts between different pieces of your code. When you mark something as private/protected, you're declaring explicitly that this thing isn't for general public consumption and no external code should be coupled to it.

This is mostly a reminder for yourself and other developers and will at worst give you light slap on the wrist if you disobey that marker; it's not an ironclad protection by any means. There are any number of ways around that, e.g. using Reflection. But, if it was made too easy to access those private parts, developers would probably be doing it left and right and negate the entire point.

Since those properties are included in the array when casting an object to an array, at the very least it's not immediately obvious how to access them directly due to the added NUL bytes. If you take the time to figure out how to access them, you hopefully really know what you're doing.

TL;DR: (I believe) it's a minimum attempt to try to enforce some minimal coding standards and not let newbies violate all OOP principles once they figure out what an array cast is.



来源:https://stackoverflow.com/questions/45756514/why-php-adds-null-bytes-to-private-and-protected-property-names

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