user2077474
user2077474

Reputation: 353

Call variable from a function that's inside a class?

I just created my first PHP class, but I'm very new to this and now I don't know how to call a variable inside a function that I created.

For example:

class Example
{
  public function testFunction() {
    $var1 = "Test";
    $var2 = "Hello";
  }
}

And then, for example, echo $var1.

I know that I can call the function through this:

$something = new Example();
$something->testFunction();

But how can I call one of those variables inside the function?

I also know that if the variable was outside the function, it would be:

$something = new Example();
echo $something->var1;

I could use a return, but that way I would end with just one variable, and I have multiple variables inside that function.

I hope that you can help me.

Upvotes: 1

Views: 1167

Answers (3)

Ja͢ck
Ja͢ck

Reputation: 173562

Variables declared inside your function are only accessible within the function body.

If your function needs to return more than one value, you either a) return a new object, or b) return an array:

return [$var1, $var2];

And in the calling code:

list($a, $b) = $something->testFunction();

Upvotes: 1

scrowler
scrowler

Reputation: 24406

To access variables from outside class functions like that, you need to set the variables as properties of the class:

class Example {
    public $var1 = ''; 
    private $var3 = ''; // private properties etc are not available outside the class

    public function testFunction() {
        $this->var1 = 'Test';
        $var2 = 'Test2';
        $this->var3 = 'Test3';
    }
}

$something = new Example();
echo $something->var1; // Test
echo $something->var2; // can't do this at all (it's not an object property)
echo $something->var3; // can't do this, it's private!

Of course, you can return whatever you like from the function itself...

public function testFunction() {
    $this->var1 = 'Test';
    $var2 = 'Test2';
    $this->var3 = 'Test3';
    return array($this->var1, $var2, $this->var3);
}

You can return private properties and locally scoped variables...

list($var1, $var2, $var3) = $something->testFunction(); // all there!  

Upvotes: 2

helion3
helion3

Reputation: 37381

Variables inside functions aren't available outside them. The function needs to return the variable.

i.e.

function getName(){
  return "helion3";
}

echo $myClass->getName();

If you need more than one, return an array:

return array("name1","name2");

Upvotes: 2

Related Questions