-3

I am currently working on my PHP skills and at the moment I'm working with classes. What I want to do is to create a class for which I can echo the object. I have the following example:

    class good_stuff {
        public function __construct() {
            return "This is a function called by a construct from a class called: " .__CLASS__;
        }
        public function __toString() {
            return $this->self::__construct;
        }
    }

    $my_object = new good_stuff();
    echo $my_object;

I guess that my __toString is returning a wrong value, but I would like to know some details as $this doesn't seem properly documented. Is the only possible solution to this issue to define a property inside good_stuff and then assign and return it via __toString?

What I want to know is more information and a brief explanation of how $this works and what I'm missing from a theoretical point of view.

gnat
  • 21,442
  • 29
  • 112
  • 288
Alex Luigi
  • 1
  • 1
  • 4

1 Answers1

2

The problem is not $this (which is documented just fine).

The problem is that you trying to invoke a constructor manually (don't do that), and returning a value from a constructor (what sense does this make?) and forgetting the () that goes with a function call, while doing so.

I don't know why you're trying to find such a complicated solution. Simply return a string from your toString() function. Have it invoke another function in turn if you want to. But not the class constructor. That is not what it is for.

If the string to be returned by toString() is to be generated by the constructor, have the constructor store it as a property.

Lightness Races in Orbit
  • 8,755
  • 3
  • 41
  • 45