This quick demo explains the basics of PHP objects, especially for use to describe entities in your application.

PHP classes define objects that have properties (which behave like variables) and methods (which behave like functions). PHP includes a built-in stdClass object. All user-defined classes extend the features of a stdClass object.

This first screenshot shows the creation of an object referenced by the $user variable. The $id property is set and the results displayed. PHP has two diagnostics commands, print_r() and var_dump() that can be used to display the properties of objects for debugging. This code also shows how to read a property from an object.

screenshot

Now we create a new class called User. Because this class contains no code, it actually performs exactly the same as our original stdClass object.

Important update: I'm leaving this step in the tutorial for demonstration purposes, but starting with PHP 8.2, dynamic properties are deprecated, so we must declare the $id as shown in the next step before we can set a value.

screenshot

By declaring a property in an object, we can make sure that property always exists in the object, whether it has been initialized with a value or not. Here we see the $id property exists in the $user object, even though it has no value.

screenshot

We can assign any value to the $id property because no type was assigned. Here we see a string value works the same was as our integer before.

screenshot

However, when we specify the int type for our property, the application crashes when we pass a string value.

screenshot

If we set our $id property to private, it cannot be written or read by the external process, so we get a fatal error when we try to assign a value to $user->id.

screenshot

We solve this problem by adding a setter method to the User class. We can now pass a value to the setId() method to be stored in the private property inside the object. The print_r() output shows that the property is set, but we cannot read the property directly, either.

screenshot

Adding a getter method allows us to retrieve the property for display.

screenshot

By default, properties can be set multiple times during execution. This is useful in most cases, but not a great idea for properties that identify database records.

screenshot

By marking a property readonly it can be set only once. Attempts to change a readonly property more than once will trigger a fatal exception.

screenshot

This is just the surface of what can be done with PHP objects, but hopefully it has provided a quick start for understanding entity definitions in your Symfony application.