3

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 Answers1

4

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.

deceze
  • 510,633
  • 85
  • 743
  • 889
  • 2
    The actual reason is disambiguation of identically-named properties declared in different classes. If private properties are involved, you can have multiple properties with the same name on a single object. – NikiC Aug 18 '17 at 18:48
  • @NikiC Why specifically `NUL` bytes then, isn't this already addressed by added asterisks? – deceze Aug 18 '17 at 19:01
  • 2
    The leading null bytes is an easy way to distinguish between public and non-public properties. The null byte after the class name makes sure that the class name is usable as a null-terminated string without requiring an explicit copy. By convention, PHP generally uses null bytes to denote various special and reserved names, including anonymous class names, create_function functions, etc. – NikiC Aug 18 '17 at 20:09
  • 2
    The way these names are generated is really an implementation detail, which leaks in the case of object-to-array casts and is now preserved for backwards compatibility reasons. I'm only explaining why this name mangling is necessary internally. – NikiC Aug 18 '17 at 20:10
  • 1
    @NikiC Great insight; a separate answer by you may be in order here. – deceze Aug 18 '17 at 20:13