get property in PHP

Discussion in 'PHP' started by benjib98, Dec 17, 2007.

  1. #1
    Hi guys,

    I am relatively new to PHP, have more experience with other OOP language. Can someone tell me how are the get, set properties handled in PHP?Tried to get some ideas, but not sure about the __get() __set() functions.
    Cheers
    Ben
     
    benjib98, Dec 17, 2007 IP
  2. sunnyverma1984

    sunnyverma1984 Well-Known Member

    Messages:
    342
    Likes Received:
    7
    Best Answers:
    0
    Trophy Points:
    120
    #2
    see php manual for details or do a google search for it
     
    sunnyverma1984, Dec 17, 2007 IP
  3. tonybogs

    tonybogs Peon

    Messages:
    462
    Likes Received:
    13
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Haha, well that isnt very helpful advice :)

    The __set and __get are used for function overloading. They're basically called if you're trying to access or read variables of an object.

    So for example, if you do something like

    echo $object->var;

    It will return run the function __get and do whatever you have defined


    Similarly, if you try

    $object->var = 'test';

    The __set function will be run.

    Hope this helps
     
    tonybogs, Dec 17, 2007 IP
  4. benjib98

    benjib98 Peon

    Messages:
    23
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #4
    well after some google-ing I had mixed feelings, but yeah tonybogs you gave an interesting answer. So I assume the following is right:
    class TestClass
    {
    private $_var;
    public function __get()
    {
    return ($_var);
    }
    }

    public function __construct($var)
    {
    $_var = $var;
    }

    $test = new TestClass('this is a test');
    //and the code below will call the __get function and print the text in the constructor?????
    echo $test->var;


    I have used another OOP language (C#), and there is a slightly different approach of properties, but I assume the code above is more likely to be OK.Please let me know your opinion.
    Thanks

    Ben
     
    benjib98, Dec 18, 2007 IP