PeeHaa
PeeHaa

Reputation: 72682

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

Upvotes: 5

Views: 1525

Answers (6)

Darsstar
Darsstar

Reputation: 1895

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.

Upvotes: 1

shelhamer
shelhamer

Reputation: 31170

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.

Upvotes: 1

Pascal MARTIN
Pascal MARTIN

Reputation: 401142

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.

Upvotes: 3

Marc B
Marc B

Reputation: 360762

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?

Upvotes: 4

dynamic
dynamic

Reputation: 48131

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

Upvotes: 1

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385274

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.

Upvotes: 11

Related Questions