OOP php新类创建,我怎么能做到


OOP php new class creating, how I can do it?

为什么我的类会给我以下错误:

解析错误:语法错误,文件中意外的"new"(T_NEW.php在第 6 行

 class mongowork {
    private $mongo = new MongoClient();
    private $db = $mongo->wiki;
    public  $col = $db->articles;
    public function mongocheck($title) {
        $res = $this->$col->find(array('title' => $title));
        if($res->count()>0) {
            return true;
        }
        else {
            return false;
        }
    }   
}

在继续之前,您应该阅读更多 OOP php 参考资料。您的代码完全缺少构造函数。不能在类内的随机空间中为变量声明和赋值。

class mongowork {
  private $mongo;
  private $db;
  public  $col; 
   function __construct() {
      $this->mongo = new MongoClient();
      $this->db = $this->mongo->wiki;
      $this->col = $db->articles;
   }
    public function mongocheck($title) {
       //you wrote $this->$col which is wrong - it should be $this->col
        $res = $this->col->find(array('title' => $title)); 
        if($res->count()>0) {
            return true;
        }
        else {
            return false;
        }
    }
}

我无法在这里解释所有概念。上面的代码现在应该可以工作了。但请开始阅读它。它真的会有所帮助!

属性必须是常量值:http://php.net/manual/en/language.oop5.properties.php

此声明可能包括初始化,但 初始化必须是一个常量值,也就是说,它必须能够 在编译时计算,并且不得依赖于运行时 信息以便进行评估。

您应该将值传递到对象__construct() method中或设置它们。