Anyone else having problem with magic methods?

Hey,

I’m using magic methods: __call, __set and __get. Actually, I’m using __call to do the work of set and get. The problem is that it’s not working when a get or set to a property is called from within a require. Let me show you what I mean:


class foo {
  private $name = 'John';

  public function __call($name, $args) { ... }
}

class bar extends foo {
  private $check = '$20.00';
}


require_once 'bar.php';

$bar = new bar();
require_once 'html.php'; // here the issue comes in

html.php


echo $bar->getCheck();

Returns an error. Undefined property. In order for it to work, I need to define it, but then, what’s the point of the magic concept for ? :nono:


class bar extends foo {
  private $check = '$20.00';

  public function getCheck() {
    return $this->check;
  }
}

If I try to use call getCheck() outside the require, it works


require_once 'bar.php';

$bar = new bar();
require_once 'html.php'; // problem still exist here unless defined

echo $bar->getCheck(); //works perfectly

Anyone else run into this? It defeats the whole purpose of these magic methods really.

Because __call can do both for me.

$check is in bar, so even if it was protected, it wouldn’t have access through foo, unless I specifically add a functionality for that.

If you notice, I’m instantiating bar.

So your __call method does something like:

public function __call($name, $args)
{
	if (substr($name, 0, 3) == 'get')
	{
		// Remove the 'get'
		$property = strtolower(substr($name, 3));
		
		return $this->$property;
	}
}

? Why not just use __get?

Anyway, have you tried making the $check variable protected instead of private? If it’s private, then the foo class won’t have access to it.