PHP - passing variables to classes

我怕爱的太早我们不能终老 提交于 2021-01-20 20:01:11

问题


I trying to learn OOP and I've made this class

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

}

and I call this somewhere inside the another_class class like

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

But I don't know how to access $bla, $foo inside the do_stuff 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;

Please don't pass by reference in PHP 5, there is no need for it and I've read it's actually slower.

I declared the variable in the class, though you don't have to do that.



来源:https://stackoverflow.com/questions/4877851/php-passing-variables-to-classes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!