简体   繁体   English

PHP 严格标准:这不好吗?

[英]PHP strict standards: is this bad?

When I create a standard class I mostly do:当我创建一个标准 class 我主要做:

$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;这是一个很大的禁忌: $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编辑错字

Is it a big no-no to do: $test = null;这是一个很大的禁忌:$test = null; to do what I want?做我想做的事?

Yes.是的。

It's allowed because PHP is loose, but turning on strict mode gives you the god's-honest truth.这是允许的,因为 PHP 是松散的,但打开严格模式会给你诚实的真理。

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?这只是最佳实践的问题吗?

Yes.是的。

Something else?还有什么?

It's right .没错

null is not an object. null不是 object。 You'd essentially doing:你基本上会做:

$test = 'this is not an object';
$test->suddenly_it_is_an_object = true;

... and you wonder why you get warnings? ...您想知道为什么会收到警告吗?

Using this:使用这个:

$test = null;

You are not making clear (to both the PHP engine, and people who will read your code) that $test is an object.您没有明确说明(对于 PHP 引擎和将阅读您的代码的人) $test是 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.所以,作为一个读者,后来发现$test被用作 object 感觉并不自然——这意味着你的代码比你明确声明$test为 object 时的代码更难维护。

It's awfully bad to do and to read that = null;这样做和阅读它是非常糟糕的= null; go with the standard new...; go 带标准new...;

If you make a habit of actually declaring your objects correctly with $test = new stdClass();如果您养成使用$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.那么看到这个严格模式错误将帮助您捕获 PHP 在您不小心为$user键入$usr等时喜欢向您抛出的隐式变量声明错误,从而为您节省不必要的麻烦。

You could cast something to an object like this:您可以像这样将一些东西投射到 object 中:

$object = (object) array(
    'id' => 5,
    'name' => 'Darsstar',
    'key' => 'value',
);

But new StdClass() is still the most strict way in doing it.但是 new StdClass() 仍然是最严格的方法。 Although I have this feeling you only want the error gone and might like this syntax better.虽然我有这种感觉,但您只希望错误消失,并且可能更喜欢这种语法。

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

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