Bummer! This is just a preview. You need to be signed in with a Basic account to view the entire video.
Adding Methods2:18 with Alena Holligan
A function inside a class is called a method. These methods tell an object how to perform certain actions. We can access class methods to perform actions on data of the individual objects.
Functions within a class are called methods.
OOP allows objects to reference themselves using the keyword variable $this. When working within the scope of a method, use the keyword $this in the same way you would use the object name outside the class. The $this keyword indicates that we want to use the object’s own properties or methods, and allows us to have access to them within the class scope.
return $this->title . " by " . $this->source;
Note: Just like accessing the property outside the class, only the keyword $this starts with the dollar sign, we don’t use the dollar sign again for the properties and methods. Together $this, with the property name, make up a single variable.
Methods are class specific functions.
As such, the individual actions that an object will perform
are defined within these class methods.
When declaring a method, we also define the visibility.
Just like we did on properties.
The naming convention for methods is also the same as property.
Remember, that means the first word starts with a lowercase letter, and
all other words start with a capital letter.
Let's go back to work spaces, and add our first method.
Start by adding our visibility keyword, public, followed by function.
See, it really is a function.
Then our method name, displayRecipe.
Just like any other function, we use the opening and closing parentheses.
Then just like with our class, we want our curly braces to start on the next line.
Within our method we describe the action we want to perform.
For our methods to really be useful, we need them to have access to the other
methods and properties of their respective objects.
PHP allows objects to reference themselves using the keyword variable $this.
When working within the scope of a method use $this
in the same way that you would use the object name, outside the class.
The $this keyword indicates that we want to use the object's own properties or
methods, and allows us to have access to them within the class scope.
Let's start by returning the title and the source properties of the current object.
Just like accessing the property outside the class,
only the keyword $this starts with a dollar sign.
We don't use it again for the properties and methods.
Together $this, with the property name, make up a single variable.
Next, we'll cover how individual objects can access these methods.
You need to sign up for Treehouse in order to download course files.Sign up