1

I don't know if this is the right place to ask this but I'm going to anyway. Recently I've been watching a series on Lynda.com called "Object-Oriented Programming with PHP" and got to a part about overloading. In this section he uses the __get and __set Magic Methods. I'm completely lost on what these are doing and am even more lost at to what the purpose of Magic Methods even do. Any help would be great!

Joe Scotto
  • 8,050
  • 7
  • 41
  • 100

1 Answers1

1

__set and __get are called when a property that you are trying to set or access is not defined in your class, or not accessible. They can be used for error handling or some other purposes (like Eloquent ORM, for example, which "magically" maps table columns to object's properties).

Let's say you have this class:

class A {

    var $a = "I'm A<br/>";

    function __get($property)
    {
        echo "You tried to access '{$property}' which does not exist!<br/>";
    } // __get

    function __set($property, $value)
    {
        echo "You tried to set '{$property}' to '{$value}', but '{$property}' is not defined<br/>";
    } // __set

}

then, do this to see the result:

$a = new A();

echo $a->a;

$a->iDoNotExist;

$a->iDoNotExistEither = "boo!";
Oliver Maksimovic
  • 2,935
  • 3
  • 28
  • 40
  • I'm still confused. If I set something like `$a->$variable = "test"` I can't get the value of it. Should I be able to? – Joe Scotto Oct 25 '15 at 21:13
  • Nevermind, I just got it. `__set($name, $value)` is setting an undefined property a value and `__get($name)` is defining that property. Please correct me if I'm wrong. – Joe Scotto Oct 25 '15 at 21:17
  • In order to use `$a->var = "test"` while `var` is not defined, you need to have `__set($property, $value)` method implemented and its body should be `$this->$property = $value`. Then you will be able to set a previously-not-existing-property and get its value later (otherwise accessing undefined property returns `NULL`. Experiment a bit to see. – Oliver Maksimovic Oct 25 '15 at 21:22
  • Yeah, I just figured that out. Is this even useful and will I ever use it? – Joe Scotto Oct 25 '15 at 21:31
  • Personally, I avoid 'magic', I prefer when things are defined :) Also, working with 'magic' properties/methods can confuse IDE's, etc. It's always good to know how stuff works so you can understand the code when you stumble upon it, but if you don't see the purpose for this in whatever project you're working on, then simply don't use it. – Oliver Maksimovic Oct 25 '15 at 21:41