Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/82.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
将对象传递到PHP构造函数时出错_Php_Syntax_Scope_Object Properties - Fatal编程技术网

将对象传递到PHP构造函数时出错

将对象传递到PHP构造函数时出错,php,syntax,scope,object-properties,Php,Syntax,Scope,Object Properties,是否可以将对象传递到PHP类的构造函数中,并将该对象设置为全局变量,该变量可由类中的其余函数使用 例如: class test { function __construct($arg1, $arg2, $arg3) { global $DB, $ode, $sel; $DB = arg1; $ode = arg2; $sel = $arg3; } function query(){ $DB->query(.

是否可以将对象传递到PHP类的构造函数中,并将该对象设置为全局变量,该变量可由类中的其余函数使用

例如:

class test {

   function __construct($arg1, $arg2, $arg3) {
      global $DB, $ode, $sel;

      $DB = arg1;
      $ode = arg2;
      $sel = $arg3;
   }

   function query(){
      $DB->query(...);
   }

}
当我尝试这样做时,我得到一个“调用非对象上的成员函数”错误。有什么办法可以这样做吗?否则,我必须将对象直接传递到每个单独的函数中


谢谢

您可能希望将它们分配给
$this
上的值

在构造函数中,您将执行以下操作:

$this->DB = $arg1;
然后在查询函数中:

$this->DB->query(...);
这同样应该通过构造函数的其他参数来完成


$this
在实例上下文中是引用当前实例的方式。还有关键字
parent::
self::
分别用于访问超类成员和类的静态成员。

通过将参数存储为对象的属性,可以非常轻松地完成此操作:

function __construct($arg1, $arg2, $arg3) {
   $this->db = arg1;
}

function f()
{
  $this->db->query(...);
}
作为旁注…
尽管这不是必需的,但通常认为最好在类内声明成员变量。它可以让您更好地控制它们:

<?php
class test {
    // Declaring the variables.
    // (Or "members", as they are known in OOP terms)
    private $DB;
    protected $ode;
    public $sel;

    function __construct($arg1, $arg2, $arg3) {
      $this->DB = arg1;
      $this->ode = arg2;
      $this->sel = $arg3;
    }

    function query(){
      $this->DB->query(...);
    }
}
?>


有关
private
protected
public
之间区别的详细信息,请参见

$db = new db();
还有一个目标:

$object = new object($db);

class object{

    //passing $db to constructor
    function object($db){

       //assign it to $this
       $this-db = $db;

    }

     //using it later
    function somefunction(){

        $sql = "SELECT * FROM table";

        $this->db->query($sql);

    }

}

行了,谢谢你的帮助!如果我想对非对象也做同样的事情呢?假设我想传入一个整数或字符串?也是这样。只要$this是一个有效的标识符(类似于有效的变量名),就可以将任何字段放在$this上。因此,您将执行
$this->name=“somestring”
$this->name=$name等。这不仅限于构造函数,类上的任何方法都可以修改
$This
上的字段。为了代码清晰起见,添加以下内容:private$db=null;然后对其进行评论(可能没有必要,因为$db应该告诉您该属性的用途):)