php syntax error, unexpected T_VARIABLE [closed]

岁酱吖の 提交于 2019-12-13 09:46:02

问题


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.



来源:https://stackoverflow.com/questions/12194156/php-syntax-error-unexpected-t-variable

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!