为什么实例化对象会将其内容打印到屏幕上?

I have a file with php class definition which looks like this:

class NewClass {
public $data = "I am a property";

    public function __construct() {
        echo "This class has been instantiated <br>";
    }

    public function __destruct() {
        echo "<br> This is the end of the class!";
    }
}

When I include it in a nother php file (with basic html code to output a page) and when I do something like $object = new NewClass; this would actually output:

"This class has been instantiated I am a property This is the end of the class!"

to the screen.

Why does something like this print out a text to a screen?

Doing $object = new NewClass is more like assigning something to a variable (to me) rather than outputing an object along with what the contents of this object are (like the $data property).

So why this works like this?

Instantiating an object doesn't print anything. Instantiating an object doesn't print object content. You print defined strings with echo statement...

Why does something like this print out a text to a screen.

Because the methods that do this printing get called, that’s why.

$object = new NewClass; creates a new object instance of this class, and in that process the constructor of the class is called - the public function __construct part in your code. (In prior PHP versions, a method with the same name as the class was automatically called as the constructor, now it is done via the reserved name __construct.) That method contains an echo statement, so you get that “This class has been instantiated” output.

(Your example should not output the “I am a property” part you said you are getting though - because that $data property containing this is not accessed anywhere. And your code as shown doesn’t actually output this, see https://3v4l.org/XKcUR)

And when the whole script ends, PHP does “garbage collection” and executes shutdown functions, to clean everything up. During that process, the destructor methods (if existing) of all still existing objects are called. That’s where the “This is the end of the class!” output in your example originates from.

You can read more about constructors and destructors here, http://php.net/manual/en/language.oop5.decon.php