1

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;
?>
1

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I will note that there is many acceptable ways of returning the variable. I am just highlighting one way where you can return an object of data that is otherwise concealed in the class (eg. private)
1

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.

1 Comment

There are myriad ways to do it, but as @MichaelBerkowski has suggested, a good refresh in PHP (and programming) basics might serve you well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.