-5

I'm trying to access the return value of the test() inside __constructor() but I stucked it. anyone Can tell me about that how can I get the return value from __constructor(). I appreciate your answer!

class some
{
    public function __construct()
    {
        $this->test(); // I want this test()
    }

    public function test() 
    {
        return 'abc';
    }
}

$some = new some;


echo $some;

print_r($some);

I tried by myself, but nothing happens!

Thanks!

Ericgit
  • 2,624
  • 2
  • 22
  • 34

2 Answers2

0

Constructors don't return values and you can't just echo an object, try this instead.

class some
{
    private $my_string;

    public function __construct()
    {
        $this->my_string = 'abc';
    }

    public function test() 
    {
        return $this->my_string;
    }
}

$some = new some;


echo $some->test();
Raul Sauco
  • 1,979
  • 3
  • 16
  • 16
0

The simple way is to implement the __toString() in your class

public function __toString()
{
    return $this->test();
}

Print your object

echo $some; // 'abc'


You can improve your code:

class Some
{
    protected $test;

    public function __construct($value)
    {
        $this->test = $value;
    }

    public function __toString()
{
    return 'Your Value: ' . $this->test;
}
}

$some = new Some('Hello World');

echo $some; // Your Value: Hello World
Khoa TruongDinh
  • 823
  • 1
  • 11
  • 24