如何将变量从一个类函数调用到另一个类函数

时间:2013-10-07 05:53:57

标签: php oop variables scope

我是php oop的新手

我有两个文件这是我的代码

1)info.php的

public $bd, $db1;    
class Connection {  
  function connect() {  
    $this->db = 'hello world';  
    $this->db1 = 'hi'  
  }  
}

2)prd.php

require_once 'info.php'
class prdinfo {  
  function productId() {  
    echo Connection::connect()->$bd;  
    echo Connection::connect()->$db1;   
  }  
$prd = new prdinfo ();  
$prd->productId ();  

我怎样才能在第二课中回应我的var 我已经尝试过这种方式,但我没有得到正确的输出

感谢

1 个答案:

答案 0 :(得分:3)

它应该是这样的。

<强> info.php的

class Connection {
   // these two variable should be declared within the class.
   protected $db; // to be able to access these variables from a diff class
   protected $db1; // either their scope should be "protected" or define a getter method.

   public function __construct() {
      $this->connect();
   }

   private function connect() {
       $this->db = 'hello world';
       $this->db1 = 'hi';
   }
}

<强> prd.php

require_once 'info.php';

// you are accessing the Connection class in static scope
// which is not the case here.
class prdinfo extends Connection {
   public function __construct() {
       // initialize the parent class
       // which in turn sets the variables.
       parent::__construct();
   }

   public function productId() {
        echo $this->db;
        echo $this->db1;
   }
}


$prd = new prdinfo ();
$prd->productId ();

这是一个基本的演示。根据您的需要进行修改。更多信息 - http://www.php.net/manual/en/language.oop5.php