开发者

PHP strict standards: is this bad?

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


Is it a big no-no to do: $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.

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. 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.


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.


It's awfully bad to do and to read that = null; go with the standard new ...;


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.


You could cast something to an object like this:

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

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜