简体   繁体   English

为什么php向私有和受保护的属性名称添加空字节?

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

I am new to PHP world and learning it from php.net . 我是PHP世界的新手,可以从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. 我知道,将对象强制转换为数组时,将ClassName星号键(*)放在数组键中的私有和受保护属性名称之前,会在私有和受保护属性名称周围添加空字节。

But my question is that WHY php add null bytes WHAT is the reason ? 但是我的问题是, 为什么 PHP添加空字节是什么原因?

Can anyone tell in simple and easy words. 任何人都可以用简单易懂的语言讲述。

Examples will help a lot. 例子会很有帮助。

Thanks 谢谢

The point of private / protected properties is that you're not supposed to access them from outside the class itself. private / protected属性的要点是,您不应从类本身之外访问它们。 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. 当您将某物标​​记为private / protected ,您在明确声明该物不供一般公众使用,并且不应将任何外部代码与其耦合。

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, eg 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. 由于将对象强制转换为数组时,这些属性包含在数组中,至少由于添加了NUL字节,如何直接访问它们至少不是立即显而易见的。 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. TL; DR :(我相信)这是尝试强制实施一些最低限度的编码标准,并且让新手弄清楚数组强制转换后,不要让新手违反所有OOP原则的最小尝试。

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

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