Peter Nosko
Peter Nosko

Reputation: 1144

php: prevent creation of object-level variables

I created a new object-level variable due to a typo. This was tough to debug. While this could be a lazy feature, is there a way to prevent object-level variables from being created by an assign? I was hoping the error_reporting would at least tell me I did it, if not prevent it.

<?php

error_reporting(E_STRICT|E_ALL);

class SearchField {
    var $field1;
}

$field = new SearchField();
$field->field1 = 'value1';
echo '<p>'.var_dump($field).'</p>';

$field->feild1 = 'value2';
echo '<p>'.var_dump($field).'</p>';

$field = new SearchField();
$field->field1 = 'value1';
echo '<p>'.var_dump($field).'</p>';


?>

Here, the typo is fairly obvious. Sometimes it not so obvious.

object(SearchField)#1 (1) { ["field1"]=> string(6) "value1" }
object(SearchField)#1 (2) { ["field1"]=> string(6) "value1" ["feild1"]=> string(6) "value2" }
object(SearchField)#2 (1) { ["field1"]=> string(6) "value1" }

Upvotes: 3

Views: 1177

Answers (1)

deceze
deceze

Reputation: 522372

You could use a magic setter:

public function __set() {
    throw new LogicException('Thou shalt not create variables on me');
}

http://www.php.net/manual/en/language.oop5.overloading.php#object.set

Though I'd question how good an idea it is to add this to all your classes just to be defensive about this one possible mistake. You should rather use protected properties and explicit getter and setter methods and get in the habit of using $field->setField('foo'), which is better OOP practice to begin with.

Upvotes: 2

Related Questions