0

Is there a way to call a function in a class without using 'call_user_func' and without eval?

here is why I ask:

When I use 'call_user_func' I get the '$this not in context' error:

$this->id = $selectId['id'];
$file = 'score_' . $this->sid . '.php'; //the file with the class

if (@include_once($file)) { //including the file

    $scoreClass = 'Score_' . $this->id;
    call_user_func($scoreClass .'::selectData', $this->user_id);
}

I can overcome this 'not in context' error calling the function like this: but now my name is not variable.

$this->id = $selectId['id'];
$file = 'score_' . $this->sid . '.php'; //the file with the class

if (@include_once($file)) { //including the file

    $test = new Score_98673();
    $test->selectData($this->user_id);

}
1
  • 3
    Static methods are not in an object-context "Because static methods are callable without an instance of the object created, the pseudo-variable $this is not available inside the method declared as static." Commented Apr 16, 2013 at 13:22

2 Answers 2

3
call_user_func(array($score, 'selectData'), $this->user_id);

This is the correct syntax for the callable pseudotype.
http://php.net/manual/en/language.types.callable.php

You can also do this, BTW:

$method = 'selectData';
$score->$method($this->user_id);
Sign up to request clarification or add additional context in comments.

3 Comments

Don't forget to indicate that he can instantiate the class with $class = new $scoreClass;
When I use the first example I still get: "Using $this when not in object context" When I use the second example I will get this error: "Call to a member function selectPDFData() on a non-object"
@Boni $score will of course have to be an instance of the class, an object. Without instantiating an object you cannot call instance methods on it. In your example that's $test.
1
if (@include_once($file)) { //including the file
    $scoreClass = 'Score_' . $this->id;
    $test = new $scoreClass();
    $test->selectData($this->user_id);
}

This is all you have to do. As you can use variable class names when using new.

The above fails as you call a non-static method (should throw some error) which uses $this.

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.