user3338143
user3338143

Reputation: 81

Using variables inside functions that are in a class

Im trying to call a variable that is being created in the function , how can i access this variable?

<?php

class youtube
{
    public function details()
    {
           $test = "asdas";
    }
}
$class = new youtube();
$s = $class->details()->test;
echo $s;
?>

Upvotes: 1

Views: 51

Answers (2)

hammus
hammus

Reputation: 2612

As @Feroz has suggested, you're not returning anything from the details() method:

class youtube
{
    public function details()
    {
           $test = "asdas";
           return $test;
    }
}
$class = new youtube();
$s = $class->details();
echo $s;

or

class youtube
{
    public $test;
    public function details()
    {
           $this->test = "asdas";
           return $this;
    }
}
$class = new youtube();
$s = $class->details()->test;
echo $s;

Further reading on variable scope can be found in the documentation.

Upvotes: 1

Turnerj
Turnerj

Reputation: 4278

There is a couple of ways you can do it however I would do something like this.

<?php

class youtube
{
    private $details = array(
        'test' => null
    );
    public function details()
    {
        return $this->details;
    }
}

$class = new youtube();
$s = $class->details()->test;
echo $s;

Basically I am storing a details property which contains various properties and I just return this object.

Upvotes: 2

Related Questions