问题
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