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. 0:00 As such, the individual actions that an object will perform 0:03 are defined within these class methods. 0:07 When declaring a method, we also define the visibility. 0:10 Just like we did on properties. 0:14 The naming convention for methods is also the same as property. 0:16 Camel case. 0:21 Remember, that means the first word starts with a lowercase letter, and 0:22 all other words start with a capital letter. 0:26 Let's go back to work spaces, and add our first method. 0:29 Start by adding our visibility keyword, public, followed by function. 0:33 See, it really is a function. 0:39 Then our method name, displayRecipe. 0:42 Just like any other function, we use the opening and closing parentheses. 0:48 Then just like with our class, we want our curly braces to start on the next line. 0:53 Within our method we describe the action we want to perform. 1:00 For our methods to really be useful, we need them to have access to the other 1:05 methods and properties of their respective objects. 1:10 PHP allows objects to reference themselves using the keyword variable $this. 1:13 When working within the scope of a method use $this 1:20 in the same way that you would use the object name, outside the class. 1:23 The $this keyword indicates that we want to use the object's own properties or 1:28 methods, and allows us to have access to them within the class scope. 1:34 Let's start by returning the title and the source properties of the current object. 1:40 Just like accessing the property outside the class, 1:58 only the keyword $this starts with a dollar sign. 2:01 We don't use it again for the properties and methods. 2:05 Together $this, with the property name, make up a single variable. 2:09 Next, we'll cover how individual objects can access these methods. 2:14
You need to sign up for Treehouse in order to download course files.Sign up