1

As a good practice, should ALL my overloaded __get functions look like this example from https://www.php.net/manual/en/language.oop5.overloading.php#object.isset and include the debugging code?

public function __get($name)
{
    echo "Getting '$name'\n";
    if (array_key_exists($name, $this->data)) {
        return $this->data[$name];
    }

    /*question specific code from here on*/

    $trace = debug_backtrace();
    trigger_error(
        'Undefined property via __get(): ' . $name .
        ' in ' . $trace[0]['file'] .
        ' on line ' . $trace[0]['line'],
        E_USER_NOTICE);
    return null;
}

It seems like it could end up being a lot of duplicate code if included in every class I overload.

1
  • Have you thinked about inheritance or static helper classes? Commented Feb 24, 2012 at 1:45

5 Answers 5

1

No. Your overloaded __get functions do not need to look like this example, at all.

IMHO, it is a good idea to avoid these magical functions. They seem attractive, but using this "magic" leads to hard-to-maintain code. At least, this was my experience.

One of the "principles" I "follow" today is to have "IDE-friendly" classes. I mean: if I am using Eclipse PDT, and a $variable is of a given class, the auto-complete should show to mee all methods and properties available. Using these magic methods, we can never tell what is available.

This is merely a general advice, which may not apply to your specific case.

Sign up to request clarification or add additional context in comments.

Comments

0

I would throw an exception instead of doing a debug_backtrace() and trigger_error().

It's situational though. You may wish to do something else entirely if the key doesn't exist.

Comments

0

There is no "good practice" on such case.

Depending on the object expected behaviour (it depends on the task, nothing more) you:

  1. Trigger notice/warning (as in your example)
  2. Throw an exception
  3. Return null (or some other predefined value)

Comments

0

No. This example takes what would be member variables and stores them in an array member variables. You should not overload that everywhere. You should be putting this in parent classes and letting it get inherited.

Also, the output being an triggering an error is old school. Make a new exception class and throw it instead, such as PropertyNotFoundException.

Comments

0

You could wrap whatever exception handling you end up using in a global utility function which would be a bit DRYer. You can also use an AOP library to inject this functionality in your existing classes.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.