【问题标题】:PHP - passing variables to classesPHP - 将变量传递给类
【发布时间】:2011-06-20 03:44:08
【问题描述】:

我正在尝试学习 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

【问题讨论】:

标签: php oop class function


【解决方案1】:
<?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 中通过引用传递,不需要它,我已经阅读它实际上更慢。

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

【讨论】:

  • 就像@Logan 说的那样——底线是如果你想保存一些信息——那么你需要把它保存在本地类中。
  • 我不会做出笼统的声明“不要在 PHP5 中通过引用传递”。也许不是为了组合,但如果你想修改一个数组怎么办?通过引用传递有它的优势。
  • 您可能应该说“很少需要它”。在大多数情况下,这是不必要的。
【解决方案2】:

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

【讨论】:

    【解决方案3】:

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

    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);
      }
    
    }
    

    【讨论】:

    • "为了向后兼容,如果 PHP 5 找不到给定类的 __construct() 函数,它将通过类的名称搜索旧式构造函数。实际上,这意味着唯一会出现兼容性问题的情况是,如果该类有一个名为 __construct() 的方法,该方法用于不同的语义。” -PHP Constructors and Destructors。使用新语法仍然是一个好主意,因为将来可能会放弃向后兼容性。
    • @zzzzBov 对,我永远不会告诉某人开始使用已弃用的东西。 IMO 这种风格更清晰。
    • 我只是想澄清@Alexandra 的代码为何有效(对于构造函数)。
    • 还有什么人还在使用 PHP
    【解决方案4】:

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

    $this->foo = $some_normal_variable
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-01-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-23
      • 2013-06-09
      • 2013-02-19
      相关资源
      最近更新 更多