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

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

本文介绍了为什么php在私有和受保护的属性名称中添加空字节?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是PHP世界的新手,可以从 php.net 中学习它.我知道当将对象转换为数组时,在 ClassName 星号键(*)之前,在私有和受保护的属性名称周围会添加空字节,并且数组键中受保护的属性名称.

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.

但是我的问题是为什么 php添加空字节原因是什么?

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

任何人都可以用简单易懂的语言讲出来.

Can anyone tell in simple and easy words.

例子会很有帮助.

谢谢

推荐答案

private/protected属性的要点是,您不应从类本身之外访问它们.这不是安全措施或类似措施,而是在代码的不同部分之间强制执行合同.当您将某事物标记为private/protected时,您在明确声明该事物不是供一般公众使用的,并且不应将任何外部代码与其耦合.

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.

由于将对象强制转换为数组时这些属性包含在数组中,至少由于添加了NUL个字节,如何直接访问它们至少不是立即显而易见的.如果您花时间弄清楚如何访问它们,则希望您真的知道自己在做什么.

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 :(我相信)这是尝试强制实施一些最低限度的编码标准的一种最小尝试,并且一旦让新手弄清了数组强制转换是什么,就不要让新手违反所有OOP原则.

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.

这篇关于为什么php在私有和受保护的属性名称中添加空字节?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 06:19