Powering Up with Attributes and Methods

Powering Up with Attributes and Methods

Wonderful to see you back here! Having established a basic understanding of classes and objects from the last lesson, we’re now ready to add more power to our Spacecraft class. Just like in the real world, where a spacecraft has unique features and can perform various actions, we can do the same in our code by adding attributes and methods.

Before we dive into enhancing our Spacecraft class, let's break down what attributes and methods are!

Attributes

Attributes, also known as properties or fields, are variables that belong to a class. They are used to store data relevant to objects created from the class. For our Spacecraft class, an attribute could be something like name, speed, or fuelLevel.

Attributes allow each instance of a class (each object) to have its own set of data. When defining an attribute, we use the public keyword to set its visibility, meaning it can be accessed from outside of the class. Don't worry too much about the different visibility levels right now; we'll cover them in a future lesson.

Here's an example:

<?php
class Spacecraft {
    public $name; // This is an attribute
}
?>

This code snippet defines an attribute called name for the Spacecraft class, which can store the name of each spacecraft.

Methods

Methods are functions that belong to a class. They are used to define behaviors or actions that objects of the class can perform. For instance, a Spacecraft might have methods like launch(), land(), or refuel().

Methods can utilize and modify the object's attributes through the $this keyword, which refers to the current instance of the class. When defining a method, we also use the public keyword to set its visibility, meaning it can be called from outside of the class. Again, we'll talk more about different visibility levels in an upcoming lesson.

Here's an example:

<?php
class Spacecraft {
    public $name;

    public function launch() { // This is a method
        echo $this->name . " is launching!";
    }
}
?>

In this example, the launch method utilizes the name attribute via the $this keyword to output a message indicating that a spacecraft is launching.

Attributes store the state of an object, while methods define the behavior. Together, they make objects truly powerful and versatile components in your software. Now, let's move on to adding these elements to our Spacecraft class.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal