0

我是 php oop 的新手

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

1)信息.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我已经尝试过这种方式,但我没有得到正确的输出

谢谢

4

1 回答 1

3

它应该是这样的。

信息.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

于 2013-10-07T06:03:33.190 回答