php syntax error, unexpected T_VARIABLE [closed]

2019-09-19 09:39发布

问题:

code:

public function isQuestion($query){

    $questions = $this->getAllQuestions();

    if (count($questions)){
            foreach ($questions as $q){
                if ($this->isQuestion$q($query)){
                    return $this->isQuestion$q($query);
                }
            }
        }

    return false;
}

error:

Parse error: syntax error, unexpected T_VARIABLE in /Applications/XAMPP/xamppfiles/htdocs/ai/application/models/question_model.php on line 7

the problem occurs on

if ($this->isQuestion$q($query)){

return $this->isQuestion$q($query);

i have some functions like isQuestion1, isQuestion2, isQuestion3 etc... and i call another function *getAllQuestions* that will return me all the numbers of the questions in an array like 1,2,3,4,5... then i use the above code to check if each function is a question based on a query

回答1:

Well, the following is invalid syntax:

if ($this->isQuestion$q($query)){

Try this instead:

foreach ($questions as $q) {
    if ($result = $this->{'isQuestion' . $q}()) {
        return $result;
    }
}
return false;


回答2:

The problem is with your method isQuestion$q.

The $ denotes the start of a variable and is confusing the interpreter.

Write it like so:

isQuestion{$q}

The curly braces allow you to insert a variable into a string (or anything with string representation). Read Curly braces in string in PHP for more information.



回答3:

If you need to call a function with a dynamic name, have a look at http://de2.php.net/manual/en/function.call-user-func-array.php or http://de2.php.net/manual/en/function.call-user-func.php

You might want to ensure that the method really exists in order to avoid getting fatal errors: http://de2.php.net/manual/en/function.method-exists.php

Also check if you want to replace

if ($this->isQuestion$q($query)){
    return $this->isQuestion$q($query);
}

with

if ($this->isQuestion$q($query)){
    return true;
}

In general it might be better to create an interface Question and hold an array with the Question instances to be asked.