簡體   English   中英

如何從一個類函數調用變量到另一個類函數

[英]how to call a variable from one class function to another class function

我是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我已經嘗試過這種方式,但是我沒有得到正確的輸出

謝謝

應該是這樣的。

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/zh/language.oop5.php

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM