Accessing Properties3:14 with Alena Holligan
Once we create an object, we can access its properties. Getting or setting an object's properties can be done in a number of ways. In this video, we’ll be looking at the most direct way.
Object-Operators allow us to access the properties and methods of a class. We reference the object name, the object-operator, and finally the property name. The object-operator consists of the characters dash and greater than, which together make a single arrow (->).
$recipe->source = "Grandma Holligan";
Note that the property name does not start with the $ sign; only the object name starts with a $, because this entire reference is one variable.
Once we create an object, we can access its properties. 0:00 We reference the object name, followed by the characters dash and 0:05 greater than, which together make a single arrow. 0:11 And finally, the property name. 0:14 Note that the property name does not start with the dollar sign. 0:18 Only the object name starts with the dollar sign, 0:22 because this entire reference is one variable. 0:26 Because multiple instances or 0:29 objects of a class can exist if the individual object is not referenced, 0:31 the script would be unable to determine which object to read from. 0:37 We can then interact with this property just like we would any other variable. 0:42 To display this property, we can type echo before it. 0:47 To set the property, we use the object. 0:52 The single arrow, the property name, the equal sign, and then our value. 0:57 Let's print this property again. 1:09 Now let's check this out in our console. 1:17 We now see Alina Holligan, Grandma Holligan. 1:24 The power of OOP becomes apparent 1:28 when using multiple instances of the same class. 1:31 More than one object can be built from the same class at the same time, 1:35 each one independent of the others. 1:40 Let's create a second object. 1:44 We'll name this recipe2. 1:47 We can then set the source for recipe2. 1:55 Now let's print the source for both recipe1 and recipe2. 2:06 Now let's run the script in the console. 2:21 $recipe1->source was first initialized with the default value Alena Holligan. 2:25 We then changed that value to Grandma Holligan. 2:31 Then we created a second recipe and set its source to Betty Crocker. 2:35 This had no effect on recipe1, because recipe1 and recipe2 are separate entities. 2:40 This makes for 2:48 easy separation of different pieces of code into small related bundles. 2:48 Great job. 2:54 We set up our recipe class to contain all the properties of a recipe object, and 2:55 we demonstrated how we can create individual objects that exist 3:00 independently of other objects and can have their own property values. 3:04 Next, we want to set up the actions our object will perform. 3:10
You need to sign up for Treehouse in order to download course files.Sign up