magic method"s __set().

magic method"s __set().

am 04.10.2007 17:18:50 von Mads Lee Jensen

is it the __set() purpose to be called if a property exists in the
object but is out of the scope.
or is it only to be used for 'undefined instance properties'.

test:

class Magic_Set
{
public $fornavn = '';
private $efternavn = '';

public function __set($varName, $value)
{
if (property_exists($this, $varName)) {
echo 'edit ['.$varName.'='.$this->$varName.']
to ['.$varName.'='.$value.']';
}
else {
echo 'defining ['.$varName.'='.$value.']';
}
$this->$varName = $value;
}
}

$test = new Magic_Set();

$test->fornavn = 'mads';
$test->efternavn = 'jensen';
$test->mellemnavn = 'lee';

Re: magic method"s __set().

am 04.10.2007 21:51:51 von Patrick Brunmayr

On 4 Okt., 17:18, Mads Lee Jensen wrote:
> is it the __set() purpose to be called if a property exists in the
> object but is out of the scope.
> or is it only to be used for 'undefined instance properties'.
>
> test:
>
> class Magic_Set
> {
> public $fornavn = '';
> private $efternavn = '';
>
> public function __set($varName, $value)
> {
> if (property_exists($this, $varName)) {
> echo 'edit ['.$varName.'='.$this->$varName.']
> to ['.$varName.'='.$value.']';
> }
> else {
> echo 'defining ['.$varName.'='.$value.']';
> }
> $this->$varName = $value;
> }
>
> }
>
> $test = new Magic_Set();
>
> $test->fornavn = 'mads';
> $test->efternavn = 'jensen';
> $test->mellemnavn = 'lee';

Hi

The __set() magic function is called whenever an undefined class
variable is set

class Foo
{
public function __set($sProp, $Val)
{
if(in_array($sProp, $this->arrProps)){
echo "Found Class Property '$sProp'
";
}
else{
echo "Invalid Prop '$sProp'
";
$this->{$sProp} = $Val; // define it ;)
}
}

protected $arrProps = array("FirstName", "LastName");

public $Test = "";
}

$Foo = new Foo();
$Foo->FirstName = "Hugo";

// __set gets called
$Foo->tName = "Hugo";

// tName is defined
echo $Foo->tName;

// no __set gets called
$Foo->tName = "Hugo3";

echo $Foo->tName;

// no __set gets called because of object member
$Foo->Test= "no set calles";
?>

hope this helps