2013-10-07 38 views
0

我是新的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(); 

我怎么可以回声我在二等变种我已经以这种方式尝试,但我没有得到正确的输出

感谢

+6

这两个类中没有一个是首要的有效类声明 –

+1

您是否希望productId方法是静态的? –

+1

第一步你需要在类中声明公共变量。然后使用extends来扩展第二个类中的第一个类以访问基类变量 – Nes

回答

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

+0

可能会帮助提及他们有的错误,其中有一些 –

+0

当然,会这样做。 –

+0

''echo $ this - > $ db;'应该是'echo $ this-> db;' –