PHP - 将变量传递给类

时间:2011-02-02 17:42:26

标签: php oop class function

我试图学习OOP而且我已经完成了这个课程

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

4 个答案:

答案 0 :(得分: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中通过引用传递,不需要它,我读过它实际上更慢。

我在课堂上声明了变量,但你不必这样做。

答案 1 :(得分:10)

好的,首先,请使用较新的样式构造函数__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->来引用它们。那是因为该属性绑定到该类的实例。这就是你要找的......

答案 2 :(得分: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);
  }

}

答案 3 :(得分:1)

您需要使用$ this捕获类中的值:

$this->foo = $some_normal_variable