PHP 严格标准:这不好吗?
当我创建标准类时,我主要这样做:
$test = null;
$test->id = 1;
$test->name = 'name';
但是在严格模式下我收到错误。
显然,正确的做法是:
$test = new stdClass();
$test->id = 1;
$test->name = 'name';
所以我想知道:
这是一个很大的禁忌: $test = null;
做我想做的事吗?
遵守严格的标准我们能得到什么?它是否确保代码在未来版本中继续工作?向后兼容会更好吗?这只是最佳实践的问题吗?还有别的事吗?
编辑 打字错误
When I create a standard class I mostly do:
$test = null;
$test->id = 1;
$test->name = 'name';
However in strict-mode I get an error.
So obviously the correct way of doing it is:
$test = new stdClass();
$test->id = 1;
$test->name = 'name';
So I am wondering:
Is it a big no-no to do: $test = null;
to do what I want?
What do we gain by conforming to the strict standards? Does it make sure code will keep on working in future versions? Will it be better backwards compatible? Is it just a matter of best practice? Something else?
EDIT
typo
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
是的。
这是允许的,因为 PHP 是宽松的,但打开严格模式会给你诚实的事实。
是的。
这是正确。
Yes.
It's allowed because PHP is loose, but turning on strict mode gives you the god's-honest truth.
Yes.
It's right.
null
不是一个对象。您基本上会做:...并且您想知道为什么会收到警告?
null
is not an object. You'd essentially doing:... and you wonder why you get warnings?
使用这个:
您没有明确(向 PHP 引擎和将阅读您代码的人)
$test
是一个对象。因此,作为读者,后来发现
$test
被用作对象是不自然的 - 这意味着你的代码比以前更难维护您明确将$test
声明为对象。Using this :
You are not making clear (to both the PHP engine, and people who will read your code) that
$test
is an object.So, it doesn't feel natural, as a reader, to later find out that
$test
is used as an object -- which means your code is less maintenable than when you are explicitely declaring$test
as an object.执行和读取
= null;
与标准new ...;
是非常糟糕的It's awfully bad to do and to read that
= null;
go with the standardnew ...;
如果您养成了使用 $test = new stdClass(); 正确声明对象的习惯,那么看到这个严格模式错误将帮助您捕获 PHP 喜欢在以下情况下向您抛出的隐式变量声明错误:您不小心输入了
$usr
来代替$user
等,从而避免了不必要的麻烦。If you make a habit of actually declaring your objects correctly with
$test = new stdClass();
then seeing this strict-mode error will help you catch implicit variable declaration errors that PHP loves to throw at you when you accidentally type$usr
for$user
and the like, saving you pointless headaches.您可以将某些内容强制转换为这样的对象:
但是 new StdClass() 仍然是最严格的方法。
尽管我有这种感觉,但您只想让错误消失并且可能更喜欢这种语法。
You could cast something to an object like this:
But new StdClass() is still the most strict way in doing it.
Although I have this feeling you only want the error gone and might like this syntax better.