2011-02-02 118 views
6

我努力学习OOP和我做了这个类PHP - 传递变量的类

class boo{ 

    function boo(&another_class, $some_normal_variable){ 
    $some_normal_variable = $another_class->do_something(); 
    } 

    function do_stuff(){ 
    // how can I access '$another_class' and '$some_normal_variable' here? 
    return $another_class->get($some_normal_variable); 
    } 

} 

,我把这个地方的another_class类中像

$bla = new boo($bla, $foo); 
echo $bla->do_stuff(); 

但我不知道如何访问do_stuff函数内部$ BLA,$ foo的

+5

*(参考)* [类和对象基础知识(HTTP:// WWW .php.net/manual/en/language.oop5.basic.php) – Gordon 2011-02-02 17:45:24

+0

阅读http://docs.php.net/this上的$ this! – rik 2011-02-02 17:47:22

回答

12
<?php 
class Boo 
{ 

    private $bar; 

    public function setBar($value) 
    { 
     $this->bar = $value; 
    } 

    public function getValue() 
    { 
     return $this->bar; 
    } 

} 

$x = new Boo(); 
$x->setBar(15); 
print 'Value of bar: ' . $x->getValue() . PHP_EOL; 

请不要在引用传递PHP 5,没有必要,我读过它实际上比较慢。

我在类中声明了变量,尽管你不必这样做。

+0

就像@Logan说的 - 底线是如果你想保存一些信息 - 那么你需要将它保存在本地的类。 – Mikhail 2011-02-02 17:47:14

3

在PHP中,构造函数和析构函数是用特殊名称编写的(分别为__construct()__destruct())。使用$this->访问实例变量。这是你的类的重写使用此:

class boo{ 

    function __construct(&another_class, $some_normal_variable){ 
    $this->another_class = $another_class; 
    $this->some_normal_variable = $another_class->do_something(); 
    } 

    function do_stuff(){ 
    // how can I access '$another_class' and '$some_normal_variable' here? 
    return $this->another_class->get($this->some_normal_variable); 
    } 

} 
9

好吧,首先,使用新的风格构造__construct,而不是与类名的方法。

class boo{ 

    public function __construct($another_class, $some_normal_variable){ 

其次,回答您的具体问题,你需要使用member variables/properties

class boo { 
    protected $another_class = null; 
    protected $some_normal_variable = null; 

    public function __construct($another_class, $some_normal_variable){ 
     $this->another_class = $another_class; 
     $this->some_normal_variable = $some_normal_variable; 
    } 

    function do_stuff(){ 
     return $this->another_class->get($this->some_normal_variable); 
    } 
} 

现在,请注意,成员变量,类里面,我们通过与$this->前缀来引用它们。那是因为这个属性必然是这个这个类的实例。这就是你要找的内容...

1

您需要捕获使用$这个班上值:

$this->foo = $some_normal_variable