Reputation: 6234
<?php
class Test{
public $test_1, $test_2;
}
$object = new Test();
$object->test_1 = "THIS IS A TEST";
$object->test_2 = "THIS IS A TEST 2";
$object->test_3 = "THIS IS A TEST 3";
var_dump($object);
As you can see I don't have a variable called test_3. But I am not getting an error. It is working perfectly. Why? This is the output I am getting.
object(Test)#1 (3) {
["test_1"]=>
string(14) "THIS IS A TEST"
["test_2"]=>
string(16) "THIS IS A TEST 2"
["test_3"]=>
string(16) "THIS IS A TEST 3"
}
Upvotes: 1
Views: 33
Reputation: 219804
In PHP you can create public member variables on the fly. If you want to prevent this you can overload the __set()
magic method and throw an exception if someone tries to do this:
class Test{
public $test_1, $test_2;
public function __set($name, $value) {
throw new \Exception('You cannot do this!');
}
}
Upvotes: 4