I am creating a class with several input checks, and I decided to place them inside the __set method (I'm not sure if this is the correct form, since I have limited OOP experience). This seems to work fine, throwing the correct errors when invalid values ββare passed from outside the class. However, if the variable is changed inside the class, the _ _set method seems to be ignored by alltogether.
Any insight would be greatly appreciated.
//RESULT::::::::::::::::::::::::::::::: // PASS: Testing : hello // PASS: Testing exception handling // __SET: Setting b to 123 // PASS: Testing with valid value: 123 // FAIL: Testing exception handling World2 <?php class Test { public $a; private $b; function __set( $key, $val ) { switch( $key ) { case 'b': if( !is_numeric( $val ) ) throw new Exception("Variable $b must be numeric"); break; } echo ( "__SET: Setting {$key} to {$val}<br/>" ); $this->$key = $val; } function __get( $key ) { return $this->$key; } function bMethod() { $this->b = "World2"; } } $t = new Test(); //testing a try { $t->a = "hello"; echo "PASS: Testing $a: {$t->a}<br/>"; } catch( Exception $e) { echo "FAIL: Testing $a"; } //testing b try { $t->b = "world"; echo "FAIL: Testing $b exception handling<br/>"; } catch( Exception $e ){ echo "PASS: Testing $b exception handling<br/>"; } //testing b with valid value try { $t->b = 123; echo "PASS: Testing $b with valid value: {$t->b}<br/>"; } catch( Exception $e) { echo "FAIL: Testing $b"; } //bypassing exception handling with method try { $t->bMethod("world"); echo "FAIL: Testing $b exception handling {$t->b}<br/>"; } catch( Exception $e ) { echo "PASS: Testing $b exception handling<br/>"; }
oop php
thatcanadian
source share