No more Mr. Nice Guy. We're going to finish talking about setting up classes, and we're going to use full OO type notation. Don't worry, it ain't that hard. But it looks way weird, so don't freak.
Last month, we went thru a PHP script that allowed us to instantiate an object in a class. But we did a very simple example, one that was not completely OO. Still, it let you see a couple of important things.
But now we want to move forward and take that simple definition and make it just a hair more complex, and by extension, more OO pure and powerful. Well, powerful is a relative term. It can't be used as a weapon or anything like that.
Over the past few tips, I have tried to slowly add detail so that you were able to remember things and not be inundated with stuff you didn't understand. My experience is that most PHP articles throw everything but the kitchen sink at you right off the bat, and I'm left looking dazed and saying "whaaaaa" when it's over. So I tried a layered approach to make it simpler. Honestly not sure that worked. but it's too late now. One thing I definitely want to do is thank Chris Ringer, who was kind enough to act as a sounding board on this.
Maybe I should just get started and list the new code for you. Please note, the line numbers are for reference, they are not really part of the script. That's if you are like Drax and need everything to be really literal. We will start with the Class definition.
0 <?php
1 class name
2 { private $_firstName;
3 private $_lastName;
4
5 public function __construct($pfirstName,$plastName)
6 { $this->_firstName = $pfirstName;
7 $this->_lastName = $plastName;
8 }
9
10 public function printName()
11 { echo 'My name is ' . $this->_firstName . ' ' .
12 $this->_lastName;
13 }
14 }
I know. If you're not used to it, it looks big and ugly. But it'll grow on you (yes, like a fungus—ha, ha, very funny).
Let's stop for a moment and look over the code section. If you look carefully, you'll see there are really two different pairs of property names: $_firstName and $pfirstName. Why so many, and what do they represent?
What we're looking at here is the importance of scope in PHP (and most web languages). Unlike RPG, where most variables are global, most PHP properties in the OO world are local and have a limited and very well-defined scope. Hence, you end up with multiple properties, each with its own scope. Because they have their own scope, it's even possible to use the same name for different properties, and in fact, most people when coding this up will use $_firstName for both $_firstName and $pfirstName. I have separated them only so that you can see they really would be different properties with different addresses in memory. OK?
Now, what are they? $_firstName (and $_lastName obviously) are class properties. $pfirstName and $plastName are method properties. $this->_firstName and $this->_lastName are how you reference the class properties when you're inside a method (function). In this case, we're setting the class property values to the parameter values. I like to think of the _firstName like the :firstName in an SQL Select statement, a representation of an external variable that's used inside the SQL statement.
I know this seems complex, but…well, I guess it is complex. Especially when you compare it to RPG. That is one reason why I'm so skeptical when people talk about doing "Hello World" and how simple web languages are.
The point is, when you're in the OO world, you're very much dealing with small things: classes and methods. And each thing has its own scope of control, and each scope of control has its own properties (variables). Values can flow between these various scopes, but they do so using separate properties that are stored in different addresses in memory.
Now, let's take this apart and see what we have.
Line 1
No surprise here; we have the keyword class to indicate we're setting up a PHP class and the name of that class is name. Yep, stickin' with that.
Lines 2 and 3
Then, same as last month, we define the properties (variables) that are in this class. Security level and name only. We're going to make these properties private so people can't use them directly; they have to use what are known as the "getter" and "setter" methods to access them. There's other stuff we could put, but I'm trying to keep this relatively simple. The type and length of field will be defined when we put a value in here.
These properties, $_lastName and $_firstName are the class variables. Their scope of operation is just within the class and within the functions that are in that class.
Lines 5, 6, 7, and 8: public function __construct($pfirstName, $plastName)
Then we have the constructor, the system function that allows us to create or instantiate an instance of the class (that is, create an object for this class). And you can see what the constructor includes if you look at the braces that immediately follow the invocation.
The constructor is embedded in the class so that when it (the class definition) is invoked, it will automatically call this method and create a new object to play with. Pretty spiffy, eh?
The two properties that are the parms for the constructor are the $pfirstName and $plastName. These are function-level properties (as opposed to the class-level properties we saw in 2 and 3). They only function within the method where they are defined. Generally, people will name them the exact same names as the class properties, but don't be confused. They're separate properties (variables) that are stored in separate addresses (from the class properties) and that are used in a different scope of control from the class properties. To emphasize that, I have given them different names (from the class properties).
Lines 6 and 7 are where the unfamiliarity begins, specifically
$this->_firstName = $pfirstName;
$this->_lastName = $plastName;
What we're doing here is setting the properties (variables) that are part of the method to the value passed in when the class is called (see below).
The question is, why does it use the format it does instead of just using _firstName = $pfirstName; ? The answer again, of course, is "because." Because the normal equal sign based assignment statement doesn't work within a method in a class. Because you have to use the $this-> format if you want it to work. Just because. Deal with it.
First, -> is a special symbol that's used to access properties (variables) and methods (functions) within a class or to set values for the properties. You will see this a lot. Some people refer to it as "dart," but most people just mumble as they silently read the code when they come to it.
Second, $this is a way to refer to a specific object within a class. As such, it's a way of referring to the current variable, whatever that happens to be.
Third, _firstName is essentially a representation of the property $pfirstName within the method. You don't have to create _firstName. The system does that behind the scenes, and you can't use it for anything except within the $this->_firstName construct.
It's as if the $pfirstName version of the variable is for external use. It can be passed into the class, and it can carry a value into the class, but for internal manipulations within the class, you have to use $this->_firstName. Again, because. Now you're getting it.
Fourth, $this->_firstName = 'anything' basically means that you are going to set the value of the first name property in the object you're creating and set it equal to what was passed into the constructor.
Lines 10–13
Then we have a second method (the constructor was the first) that prints out the echo line. Again, see how we're embedding the internal representation into the echo statement, not the external $pfirstName/$plastName representation.
And that's it. We end with a brace to close the Class definition.
Calling the Class Definition
The code to call the class is pretty simple. We're going to do the definition and the access within a single file just for simplicity, which is why the PHP delimiters <?php and ?> are split between the two code examples. Next month, we'll see how to break these two apart and make the example more like real life. Anyway, the code to access is this:
1 $_first = 'David';
2 $_last = 'Shirey';
3 $myName = new name($_first, $_last);
4 $myName -> printName();
?>
The first two lines set the values of the properties that are going to be loaded into the object by the constructor method. Note that these are not the properties used in the class. Why should we expect them to be? They're outside the class, have nothing to do with the scope of the class.
The third line calls the name class, which then issues the constructor. Note that we're passing in parameters so that we can simply set the value of those parameters before we issue the call and not have to change the class definition as the name changes; it will be taken care of by the parms.
Then, we add the access of the printName method that's defined in the class by using the -> symbol. This is a good example of how it can be used to access methods in the class and is how a method is called in PHP. There is no PHPCALL command.
I know what you're thinking. You want the class to act sort of like a subprocedure. That is, when you create a new member of the class, it should do all of the things that are part of the class. Automatically. So you would expect that all you have to do is issue the access to the class name and it will create the new object using the constructor and then print out the "My Name Is" verbiage because it would have automatically kicked off the printName method.
But that's not how it works. (Hint: Because.) Instead, think of the class as an envelope that contains a bunch of stuff that all works on the properties associated with that class. Remember, in OO, data and actions are tied together, so a class really represents a bunch of stuff you can do to a set of data elements. As a result, when you issue a new operator on a class, all it does is run the constructor. Any other method in the class has to be accessed, using the -> symbol, separately.
Your Turn
Of course, reading about it is one thing and doing it is another. So at this point, you should get out your text editor, brush it off to remove the cobwebs, and try to re-create this code.
Next month, we'll add some additional detail here, not to the class definition (that's done) but to our understanding of how this works and all that jazz. Stay tuned.
LATEST COMMENTS
MC Press Online