22
Wed, May
2 New Articles

TechTip: PHP Classes: Just When You Thought It Was Over

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

I promise, this is it, the last section of our opus on creating PHP OO classes. Finally! And believe me, no one is happier than I am. Except that now I have to decide what to write about next.

Last month, we finally got a class definition that not only was I satisfied with, but also actually worked. So what is there left to do? Not too much at this point (there really is a lot more stuff about classes that we could go into, but I'm not going there yet). But we have a few "icing" kinds of things to clean up, so let's get started.

At the end our last episode, we had the following script code all rolled up into one file.

0 <?php

1   Class name

2   {   public $firstName;

3      public $lastName;

4

5       public function __construct($firstName, $lastName)

6          {     $this->firstName = $firstName;

7                $this->lastName = $lastName;

8          }

9

10         public function printName()          

11          {   echo 'My name is ' . $this->firstName . ' ' . 12                         $this->lastName;

13         }

14    }

15

16   $firstName = 'David';

17   $lastName = 'Shirey';

18    $myName = new name($firstName, $lastName);

19    $myName -> printName();

20 ?>

What we have here is, however, actually two things, and I want to separate them.

First, the class definition, taking up lines 1–14. The class contains information on the properties (variables) that we'll be using as input (lines 2, 3), the constructor function using parms of first name and last name (lines 5–8), and a method that prints the name information (lines 10–13).

Second, on lines 16–19, we start by setting the values of the parameters we want to pass into the constructor (lines 16–17), then issue the access of the constructor method by instantiating a new class object (line 18), and finally, after the new object has been created, we access the printName method to print out the information (line 19).

The result is, if you run this file from a browser URL line, you'll get the verbiage "My Name is David Shirey" to show up on the browser page.

My question to you is, have you tried this yet? Hopefully, you will try it, because believe me, you don't learn this stuff by reading. You learn it by doing. So give it a try.

Splitting into Two Files

Of course, it really makes no sense for us to have all this logic in a single file. Typically, even though the class can't be thought of as a service program or subprocedure (but rather more like an envelope or box that contains like data and processing objects), classes are generally set up in their own files. Or at most, a group of classes will be set up in a single file. At any rate, the class is separated from the logic that will access it.

To do this, simply take lines 1–14 above, put a ?> at the end, and stick it in a file of its own. Call it what you will.

Then take lines 16–20, put a <?php on the front end, and dump it into a file of its own.

Now, one more thing needs to be added to the second file in order to pull the class definition in when it's time to run this logic, because somehow we have to tie these two together.

There are two PHP commands that can be used to pull a script into another script at run time: include and require. The difference between the two is that when you specify include and the file you're including isn't there, the calling script will continue to run. If you specify require, on the other hand, then the calling script fails.

There's also a qualifier on both commands; once and not specifying once. If you specify once, then the code is included only once, even if it's accessed multiple times in the calling script. If once is not specified, then every time the called script is needed, it will need to go get the class script and load it. The format for this is require_once or include_once.

The full syntax for the include or require is this:

require_once('/filepath.php');

Discussion of Properties in a Class

I want to talk about one more thing before we bring the curtain down on classes: data within classes. Let's go back to our example above.

Class vs. Parm Variables

On lines 2 and 3, we defined what I will call the class variables: $firstName and $lastName. We haven't given a type or picture to them. That will be done by the system when a value is assigned. The class properties are local to the class but within the class are globalthat is, every method in the class can use those properties, but the properties have no meaning outside of the class.

In our example, we used the names of these class properties as input parms on the constructor on line 5. In reality, we could have named these two parms something different because they actually are different variables. For example, Chris Ringer prefixes his parm variables with a p so they show up as $pfirstName and $plastName. In reality, whether you name these two sets of properties the same or different, they're really different data fields and can have different values simultaneously. They also have different scopes of control. The $pfirstName variables are only defined within the constructor and will not work outside of that method. The $firstName variable will work anywhere in the class. Just something to keep in mind.

Now you might be thinking, Hey, I'll just use the parm variables then and forget about the class properties. The problem is that parm variables only act in the method they are in. So with just parm properties, there's no way to move data from one method to another. Only a class-level variable can pass data through the length and breadth of the class.

$this->firstName;

The other thing we want to look at is the firstname property that shows up in the $this->firstname. Is this really a property? The answer is no, not really. Although we (I) like to take things apart into their constituent pieces, the $this->firstname must be looked at as a single term or symbol. Remember that it just means that you're referring to the value in the class of the parm $firstName. Why don't you just use $firstName? That is, instead of saying '$this->firstname = $firstName', why don't you just use $firstName and be done with it? The answer is simple. Because it doesn't work that way. You can't refer to a class variable within a subordinate method. You have to use the $this verbiage. It's like Dad always used to say: "Because, just because."

What Happens When a Class Opens and Closes

One more thing I want to mention is what happens when a class is opened or called. This is done with the "new" statement because opening a class always begins with the creation of a new object in that class. Hence, the constructor should always be a part of the class definition, and this constructor is kicked off as soon as the class opens.

After that, the class just sort of sits there. That is, it doesn't end until the script that calls it ends or we call the destructor. The destructor is the opposite of the constructor in that it closes the class and deletes all objects associated with that class that are still open. Running the destructor is important because while PHP does have garbage cleanup, it doesn't happen automatically like it does in RPG.

Also, please note that if we had coded a destructor in our example, then the new object would have been created and then immediately destroyed because our script did not stay open but rather closed very quickly. A class in a more normal PHP script, like the one we defined today by splitting the class from the class caller thingy, would be attached to a web page and would stay open for much longer (until you closed that screen).

The End…for Now

There's plenty more to learn about classes, but that's it for now. You should be able to write a class, create an object in it, assign values to that object, destroy that object, and perform methods. And for now, that's enough.

 

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: