0

methosHere is the call to a class I created :

Utils::search($idRole, $this->roles, 'getId');

in the Utils, search method :

public static function search ($needle, $haystack, $getter) {
    $found = false;
    $i = 0;

    while($i < count($haystack) || $found) {
        $object = $haystack[$i];

        if($object->$getter === $needle) {
            $found = true;
        }
    }

    return $found;
}

The haystack is an array of Role objects. Here is a part of the Role class :

class Role
{
  private $id;
  private $nom;

  public function __construct($id = 0, $nom = null) {
    $this->id = $id;
    $this->nom = $nom;
  }

  public function getId()
  {
    return $this->id;
  }
}

running the $object->$getter part I have an exception :

Undefined property: Role::$getId

I thought that was the way to call a property dynamically.. What do I do wrong ?

thank you

2
  • Since getId is a method, not a prop, you have to call it as method: $object->$getter(); Commented Oct 3, 2014 at 12:48
  • missing parenthesis () :) Commented Oct 3, 2014 at 12:49

2 Answers 2

2

try this ways:

The 1st element is the object, and the 2nd is the method.

call_user_func(array($object, $getter))

You can also do it without call_user_func:

$object->{$getter}();

Or:

$object->$getter();
Sign up to request clarification or add additional context in comments.

Comments

2

You try to call a class property which is in private scope.

You created a getter method for this property (Role::getId()). Now you have to call that method and not the property itself (which is private and can't be accessed outside the Role class instance which holds it).

So you have to use call_user_func():

$id = call_user_func(array($object, $getter));

2 Comments

call_user_function cannot help to access private method unless it called inside that object.
There is a public method Role::getId() which can be called by call_user_func().

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.