Fields

An object is assembled by its constructor, not by a scatter of assignments.

A class describes fields and methods. new User('Ann') calls __construct. Properties are declared in the class. A dynamic property that the class never declared is bad style in modern PHP with warnings, and a source of typos.

An object is passed by identifier: a method changes the same object, and no naive copy happens. That is not a & reference to a variable. Two variables may point to one object. Cloning is clone, and by default it is shallow.

A file can hold both a class and echo. That is how this lesson does it: the script creates a user and prints the name. In a service the class lives in its own file, and autoloading finds it by namespace. The training sandbox does not need autoloading.

Do not write a constructor that goes to the database and writes a file. A constructor puts the fields in order. A network call belongs to a service method that you can replace in a test. Otherwise the object cannot be created without the environment.

Practice

  1. The constructor's name

    What is a class constructor called in PHP?

    • __construct
    • create
    • main
    • new
  2. What the check sees

    The check expects exactly the line Ann, but the script prints Name: Ann. Will the check pass? Answer yes or no.

  3. The object's name

    Declare a class with a name field, create Ann and print the name.