【问题标题】:In PHP, why am I getting the "class name must be a valid object or string" error?在 PHP 中,为什么会出现“类名必须是有效的对象或字符串”错误?
【发布时间】:2018-04-23 07:25:28
【问题描述】:
    <?php
class article{
    public $title='';
    public $text='';
    public $instancesFilesmage='';
    public $currentDate='';
    public $section='';
}
//Definition of article class
for($instancesFiles=0;$instancesFiles<count(scandir("Articles/".date('y-m-d').""));$instancesFiles++){
//For each file inside the directory for today's articles, each of which corresponds to an instance of the "article" class...
        $dir="Articles/".date("y-m-d")."/".($instancesFiles+1)."";
        $artProps=scandir($dir);
    //Retrieve an array of its interior files, each of which corresponds to a property of the aforementioned instance
    for($propertiesFiles=0;$propertiesFiles<count($artProps);$propertiesFiles++){
        //For each item in "artProps", each of which corresponds to a property of the instance
        $instName="".date("y-m-d")."_".($instancesFiles+1)."";
        $$instName=new $article();
        $$instName->$currentDate=''.time().','.date("y-m-d").'';
        //This just sets defines the time and date at which the article was published, the sole property which exists independently from any file
        if(pathinfo($artProps[$propertiesFiles], PATHINFO_BASENAME)=='TITLE'){
            $$instName->$title=fgets($artProps[$propertiesFiles]);
        }
        if(pathinfo($artProps[$propertiesFiles], PATHINFO_BASENAME)=='TEXT'){
            $$instName->$text=fgets($artProps[$propertiesFiles]);
        }
        if(pathinfo($artProps[$propertiesFiles], PATHINFO_BASENAME)=='SECTION'){
            $$instName->$section=fgets($artProps[$propertiesFiles]);
        }
        //3 ABOVE CONDITIONALS:See if it is one of the properties whose definition is found by retrieving the first line of the file, and, if so, get that first line and set the property to that first line
        if(pathinfo($artProps[$propertiesFiles], PATHINFO_BASENAME)=='IMAGE'){
            $$instName->$image=$artProps[$propertiesFiles];
        }
        //1 ABOVE CONDITIONAL:See if it is an image, and set the image property of the particular instance to that file
        echo("<p>{$instName->$title}<p>");  
    }
}

?>

当我第一次启动“article”类的实例时,我收到“类名必须是有效的对象或字符串错误”。为什么?它与我使用双变量有关吗?我该如何解决这个问题?

【问题讨论】:

标签: php class oop debugging error-handling


【解决方案1】:

这里是$article() 的问题

在 PHP 中,类名没有$ 符号。只有变量会有。

在这里你尝试从变量创建一个对象,这就是你得到错误的原因。

更新

$article()article()

这里还有一件事是您将类名声明为article。始终类名应以大写字母 Article 开头。 Try to follow PHP code standards.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-13
    • 1970-01-01
    • 2016-06-17
    • 2017-08-01
    • 1970-01-01
    相关资源
    最近更新 更多