简体   繁体   中英

PHP - How to return a variable from a class method?

I don't understand the concept of getter and setter methods in PHP, pls help me out.

Let's say I have this class:

class something()
{
  public function test()
  {
    $bla = 10;
    return $var;
  }
}

How do I get the follwing code to work:

    $something->test();
    echo $bla;

Thanks!

First this:

return $var;

should be:

return $bla;

and second, the second part is wrong and should be like this:

$something = new something();
$bla = $something->test();
echo $bla;

You would need to make $bla global for that to work, which is rarely a good idea.

You would be better off returning that variable, which you could then assign to what you wish when calling the object's method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM