Page 1 of 1

about class and function __set

Posted: Fri Feb 23, 2007 2:35 am
by siyaco
i am working from Luke Welling and Laura Thomson's book
in the chapter of OOP function __set is explained. as i understand it is important to acces the attributes, and there is an example like this

Code: Select all

<?php
  class class1
  {
      var $attribute;
      function __get($name)
      {
          $this->$name;
      }
      function __set($name, $value)
      {
          if($name=='attribute' && $value >= 0 && $value <= 100)
          $this->attribute=$value;
      }               
  }
  
  $a= new class1;
  $a->attribute=110;
  echo $a->attribute;  
  
  
?>
according to code and my understanding the attribute can't be 110 because we have a if control structure (0>value>100)

but when i run this code it appears 110 on the browser.
is there a fault in code or my understanding :)

thanks all in advance

Posted: Fri Feb 23, 2007 2:53 am
by s.dot
It's doing that because you are accessing $attribute directly instead of through the __set() function.

If you did this:

Code: Select all

$a = new class1();
$a->__set('attribute', 110);
var_dump($a->attribute);
I dont think it would work.

Posted: Fri Feb 23, 2007 2:56 am
by s.dot
actually i'm probably wrong (i haven't worked with this before)

are you running php5?

Posted: Fri Feb 23, 2007 7:26 am
by Begby
Two things.

A. You have to be running php5 for this to work

B. It first checks if the property exists and is public, if its not then __set() or __get() is called. So in your code its going to set attribute directly and ignore __set(). However if you called $a->taco it would call set since taco is not defined.

Posted: Fri Feb 23, 2007 10:16 am
by siyaco
scottayy wrote:actually i'm probably wrong (i haven't worked with this before)

are you running php5?
the php version i am using is 5.1.4

i tried this;

Code: Select all

$a = new class1();
$a->__set('attribute', 110);
var_dump($a->attribute);
and it works. but here we call the function __set as i read from that book (L.W and L.T) the function __set must work directly like function __construct and __destruct()

thanks all in advance

Posted: Fri Feb 23, 2007 10:53 am
by Jenk
As begby pointed out, __set() and __get() only exist for public attributes that are not defined. Try this example:

Code: Select all

<?php

class Foo
{
    private $_data = array();

    public function __set($name, $val)
    {
        if ($val < 100 && $val > 0)
        {
            $this->_data[$name] = $val;
        }
    }

    public function __get($name)
    {
        if (!isset($this->_data[$name])) die ('invalid attribute!');
        
        return $this->_data[$name];
    }
}

?>