Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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" }
like image 395
Peter Nosko Avatar asked Feb 07 '26 10:02

Peter Nosko


1 Answers

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.

like image 84
deceze Avatar answered Feb 09 '26 01:02

deceze



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!