Jon49
Jon49

Reputation: 4606

Call external function from within class that accesses private properties

I'm trying to make my code a little drier by doing the follow in PHP:

function accessor($obj, $property) {
  return $obj->$property;
}

class SomeClass {
  private $variable;

  function variable() {
    return accessor($this, 'variable');
  }
}

$some = new SomeClass;
echo $some->variable();

The above code throws an error because the external function can't access the private variable. The code is simplified, further coding would make it more useful.

I'm not sure if this is possible but it would sure be nice!

Upvotes: 1

Views: 1090

Answers (1)

fdreger
fdreger

Reputation: 12505

What you want are traits (PHP 5.4+)- they are practically pasted into their parent classes, so they can access private state:

trait VariableThingy {
    function accessor($property) {
      return $this->$property;
    }

}

class Test {
    use VariableThingy;

    private $variable = 15;

    function variable() {
        return $this->accessor("variable");
    }
}

But no, it's not nice. It's atrocious. And the whole code is rather pointless. If you want dry, just go with a public variable. DRY and encapsulated are usually mutually exclusive.

Upvotes: 4

Related Questions