19
Fri, Apr
5 New Articles

TechTip: PHP Classes: The Final Chapter

Scripting
Typography
  • Smaller Small Medium Big Bigger
  • Default Helvetica Segoe Georgia Times

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 fungusha, 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.

David Shirey

David Shirey is president of Shirey Consulting Services, providing technical and business consulting services for the IBM i world. Among the services provided are IBM i technical support, including application design and programming services, ERP installation and support, and EDI setup and maintenance. With experience in a wide range of industries (food and beverage to electronics to hard manufacturing to drugs--the legal kind--to medical devices to fulfillment houses) and a wide range of business sizes served (from very large, like Fresh Express, to much smaller, like Labconco), SCS has the knowledge and experience to assist with your technical or business issues. You may contact Dave by email at This email address is being protected from spambots. You need JavaScript enabled to view it. or by phone at (616) 304-2466.


MC Press books written by David Shirey available now on the MC Press Bookstore.

21st Century RPG: /Free, ILE, and MVC 21st Century RPG: /Free, ILE, and MVC
Boost your productivity, modernize your applications, and upgrade your skills with these powerful coding methods.
List Price $69.95

Now On Sale

BLOG COMMENTS POWERED BY DISQUS

LATEST COMMENTS

Support MC Press Online

$0.00 Raised:
$

Book Reviews

Resource Center

  • SB Profound WC 5536 Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application. You can find Part 1 here. In Part 2 of our free Node.js Webinar Series, Brian May teaches you the different tooling options available for writing code, debugging, and using Git for version control. Brian will briefly discuss the different tools available, and demonstrate his preferred setup for Node development on IBM i or any platform. Attend this webinar to learn:

  • SB Profound WP 5539More than ever, there is a demand for IT to deliver innovation. Your IBM i has been an essential part of your business operations for years. However, your organization may struggle to maintain the current system and implement new projects. The thousands of customers we've worked with and surveyed state that expectations regarding the digital footprint and vision of the company are not aligned with the current IT environment.

  • SB HelpSystems ROBOT Generic IBM announced the E1080 servers using the latest Power10 processor in September 2021. The most powerful processor from IBM to date, Power10 is designed to handle the demands of doing business in today’s high-tech atmosphere, including running cloud applications, supporting big data, and managing AI workloads. But what does Power10 mean for your data center? In this recorded webinar, IBMers Dan Sundt and Dylan Boday join IBM Power Champion Tom Huntington for a discussion on why Power10 technology is the right strategic investment if you run IBM i, AIX, or Linux. In this action-packed hour, Tom will share trends from the IBM i and AIX user communities while Dan and Dylan dive into the tech specs for key hardware, including:

  • Magic MarkTRY the one package that solves all your document design and printing challenges on all your platforms. Produce bar code labels, electronic forms, ad hoc reports, and RFID tags – without programming! MarkMagic is the only document design and print solution that combines report writing, WYSIWYG label and forms design, and conditional printing in one integrated product. Make sure your data survives when catastrophe hits. Request your trial now!  Request Now.

  • SB HelpSystems ROBOT GenericForms of ransomware has been around for over 30 years, and with more and more organizations suffering attacks each year, it continues to endure. What has made ransomware such a durable threat and what is the best way to combat it? In order to prevent ransomware, organizations must first understand how it works.

  • SB HelpSystems ROBOT GenericIT security is a top priority for businesses around the world, but most IBM i pros don’t know where to begin—and most cybersecurity experts don’t know IBM i. In this session, Robin Tatam explores the business impact of lax IBM i security, the top vulnerabilities putting IBM i at risk, and the steps you can take to protect your organization. If you’re looking to avoid unexpected downtime or corrupted data, you don’t want to miss this session.

  • SB HelpSystems ROBOT GenericCan you trust all of your users all of the time? A typical end user receives 16 malicious emails each month, but only 17 percent of these phishing campaigns are reported to IT. Once an attack is underway, most organizations won’t discover the breach until six months later. A staggering amount of damage can occur in that time. Despite these risks, 93 percent of organizations are leaving their IBM i systems vulnerable to cybercrime. In this on-demand webinar, IBM i security experts Robin Tatam and Sandi Moore will reveal:

  • FORTRA Disaster protection is vital to every business. Yet, it often consists of patched together procedures that are prone to error. From automatic backups to data encryption to media management, Robot automates the routine (yet often complex) tasks of iSeries backup and recovery, saving you time and money and making the process safer and more reliable. Automate your backups with the Robot Backup and Recovery Solution. Key features include:

  • FORTRAManaging messages on your IBM i can be more than a full-time job if you have to do it manually. Messages need a response and resources must be monitored—often over multiple systems and across platforms. How can you be sure you won’t miss important system events? Automate your message center with the Robot Message Management Solution. Key features include:

  • FORTRAThe thought of printing, distributing, and storing iSeries reports manually may reduce you to tears. Paper and labor costs associated with report generation can spiral out of control. Mountains of paper threaten to swamp your files. Robot automates report bursting, distribution, bundling, and archiving, and offers secure, selective online report viewing. Manage your reports with the Robot Report Management Solution. Key features include:

  • FORTRAFor over 30 years, Robot has been a leader in systems management for IBM i. With batch job creation and scheduling at its core, the Robot Job Scheduling Solution reduces the opportunity for human error and helps you maintain service levels, automating even the biggest, most complex runbooks. Manage your job schedule with the Robot Job Scheduling Solution. Key features include:

  • LANSA Business users want new applications now. Market and regulatory pressures require faster application updates and delivery into production. Your IBM i developers may be approaching retirement, and you see no sure way to fill their positions with experienced developers. In addition, you may be caught between maintaining your existing applications and the uncertainty of moving to something new.

  • LANSAWhen it comes to creating your business applications, there are hundreds of coding platforms and programming languages to choose from. These options range from very complex traditional programming languages to Low-Code platforms where sometimes no traditional coding experience is needed. Download our whitepaper, The Power of Writing Code in a Low-Code Solution, and:

  • LANSASupply Chain is becoming increasingly complex and unpredictable. From raw materials for manufacturing to food supply chains, the journey from source to production to delivery to consumers is marred with inefficiencies, manual processes, shortages, recalls, counterfeits, and scandals. In this webinar, we discuss how:

  • The MC Resource Centers bring you the widest selection of white papers, trial software, and on-demand webcasts for you to choose from. >> Review the list of White Papers, Trial Software or On-Demand Webcast at the MC Press Resource Center. >> Add the items to yru Cart and complet he checkout process and submit

  • Profound Logic Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application.

  • SB Profound WC 5536Join us for this hour-long webcast that will explore:

  • Fortra IT managers hoping to find new IBM i talent are discovering that the pool of experienced RPG programmers and operators or administrators with intimate knowledge of the operating system and the applications that run on it is small. This begs the question: How will you manage the platform that supports such a big part of your business? This guide offers strategies and software suggestions to help you plan IT staffing and resources and smooth the transition after your AS/400 talent retires. Read on to learn: