PHP - passing variables to classes

这一生的挚爱 提交于 2021-01-20 19:57:50

问题


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.




回答2:


Ok, first off, use the newer style constructor __construct instead of a method with the class name.

class boo{

    public function __construct($another_class, $some_normal_variable){

Second, to answer your specific question, you need to use 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);
    }
}

Now, note that for member variables, inside of the class we reference them by prefixing them with $this->. That's because the property is bound to this instance of the class. That's what you're looking for...




回答3:


In PHP, constructors and destructors are written with special names (__construct() and __destruct(), respectively). Access instance variables using $this->. Here's a rewrite of your class to use 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);
  }

}



回答4:


You need to capture the values in the class using $this:

$this->foo = $some_normal_variable


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

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