English 中文(简体)
将物体移至PHP的构造错误
原标题:Passing Objects into PHP constructor error

是否可将物体输入PHP类的构造者,并确定该物体为可被该类其他功能使用的全球变量?

例如:

class test {

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

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

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

}

当我试图这样做时,我就有一个“因非目标”错误而担任成员职务。 是否有办法? 否则,我不得不将物体直接传递给每个人。

感谢!

最佳回答

您可能希望将其分配到<代码>的数值。

在您的构造中,你:

$this->DB = $arg1;

然后,在您的问询职能中:

$this->DB->query(...);

这一点同样应当与对贵方的其他论点一并进行。

。 也有关键词<代码> 括号:和 本身:,分别供该类中上层和静态成员的使用。

问题回答

As a side-note...
Even thought this isn t required, it is generally considered best to declare member variables inside the class. It gives you better control over them:

<?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(...);
    }
}
?>

PHP: Visibility , 详细说明 private ,protected and public/code>。

您可以轻而易举地将这一论点视为物体的财产:

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

function f()
{
  $this->db->query(...);
}

让我说,你有 object子。

$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);

    }

}




相关问题
Brute-force/DoS prevention in PHP [closed]

I am trying to write a script to prevent brute-force login attempts in a website I m building. The logic goes something like this: User sends login information. Check if username and password is ...

please can anyone check this while loop and if condition

<?php $con=mysql_connect("localhost","mts","mts"); if(!con) { die( unable to connect . mysql_error()); } mysql_select_db("mts",$con); /* date_default_timezone_set ("Asia/Calcutta"); $date = ...

定值美元

如何确认来自正确来源的数字。

Generating a drop down list of timezones with PHP

Most sites need some way to show the dates on the site in the users preferred timezone. Below are two lists that I found and then one method using the built in PHP DateTime class in PHP 5. I need ...

Text as watermarking in PHP

I want to create text as a watermark for an image. the water mark should have the following properties front: Impact color: white opacity: 31% Font style: regular, bold Bevel and Emboss size: 30 ...

How does php cast boolean variables?

How does php cast boolean variables? I was trying to save a boolean value to an array: $result["Users"]["is_login"] = true; but when I use debug the is_login value is blank. and when I do ...