23
Sat, Nov
1 New Articles

TechTip: PHP Classes: Will This Ever Be Over?

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

We're going to keep chipping away at what PHP classes are and how they can be used. So here we go for installment 3 of I don't really know how many.

 

If you tuned in to last month's PHP TechTip, you know that we talked in greater detail about how to set up a PHP class. Specifically, you found out that…

  • A class consists of both local properties (variables) and methods (or "functions" as we generally refer to them).
  • The definition of the local variables (properties) included a term to indicate the security level (public, private, protected) assigned to each variable.
  • There was no picture information for the local variables. PHP is a loosely typed language, and the type of variable we are creating is actually set when we assign a value to the variable ($name = 'Dave' defines a variable-length string element).
  • The methods or functions defined (and you can have more than one in a class) represent the actions you want PHP to take whenever a new object is created in this class. The process of creating a new object is called "instantiation" as in we will "instantiate" a new object of this class.
  • The method can also be assigned a security level (public, private, protected) just like the data. 

So far, so good. After that, things broke down just a bit. As it turns out, the code I gave you for instantiating the object didn't work as well as I had hoped. Or at all. I screwed up, and I'm sorry about that. Fortunately, Chris Ringer was careful to point out my errors (every last, single one of them), so I'm going to do this again, and this time I'll actually test the code (which I typically do anyway). I will say, in my defense, I was trying to really simplify things, but I still managed to screw it up.

What it should've looked like is this. (The line numbers are for reference, they are not part of the PHP script.)

1 Class name

2     { public $firstName;

3      public $lastName;

4

5      public function __construct($firstName, $lastName)

6      { echo 'My name is' . ' ' . $firstName . ' ' .          

7                                               $lastName;

8       }    

9      }

Now, let's take this apart and see what we have.

Line 1:

"Class" is the operator that indicates I'm defining a class, a blueprint for the objects we'll create with this class.

"name" is the name of this class. I admit that in this case it seems a bit confusing (its name is name), but I'm stubbornly hanging on to this. I'm not sure why.

There are no parms associated with the class definition, although sometimes parms may be associated with creating an object from this class. In a way, all of the data items defined in the class are its parms.

Lines 2 and 3:

Next comes the specification of the local data elements that are used in this class.

Note there's the security termin this case, publicand the name but no type or size information.

Line 5:

Next comes what I forgot in last month's example, the "constructor." The constructor is a special PHP system method that creates objects from the class blueprint. It starts with the security tag and is followed by the canned verbiage function __construct. There are two underscores in front of the construct. It also includes two parms that will be passed in whenever this constructor is called.

Lines 6 and 7:

These lines show what happens when we run the constructor. They're part of the method. Real PHP people won't like what I've done. Normally, you would just initialize the class fields and then do stuff in other methods, but I'm trying to keep this very simple, so I'm doing an echo function (to prove that the constructor has run) as part of the constructor rather than as a separate function. I'll offer a more correct and more OO and more complex-looking way to do this next month when we finally finish creating our true OO class. But for now, I'm opting for simplicity and transparency.

"echo" will print something to a web page. Constants are enclosed in quotes (single or double). The period is the concatenation symbol. The spaces in quotes are required to separate the first name and last name values. And finally, we have the variable names $firstName and $lastName.

Lines 8 and 9:

At the end, you have the closing brace for the constructor function (line 8) and the closing brace for the class definition (line 9).

And this is a class definition. One that works. Remember, it's the blueprint for an object, but the question remains: how do you create an object from this definition?

Generally, the class definition is kept in a separate file ("source member" in our language) that can then be pulled into code as it's needed. For the moment, we're going to put the code to create the object directly into this script. Just remember that generally won't be the case.

To create a member of this class, simply execute this code:

$firstName = 'David';

$lastName = 'Shirey';

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

What's happening here is very simple.

First, on lines 1 and 2, we're assigning values to the first name and last name variables.

Then, on line 3, we're taking a new variable that hasn't been defined in the class and using it to "call" the class definition. (In PHP, you can define variables on the fly, and that's what I'm doing here.) This is similar to the function call in RPG ILE. The word "new" tells the system what this variable is going to hold: it's going to hold a new object or member of a class. And the "name" tells PHP exactly what class you're instantiating a new object in. That's followed by the parms that represent the data elements defined in that class.

The result of issuing these commands will be to display the following words on the web page:

My name is David Shirey

Remember, you will run this from the URL line of a browser, and the words will appear on the blank page of that browser.

What's Next?

The above code is still a simplification of the type of code you will normally see. But again, my time is over. So look next month for a slightly more rigorous formulation of this. For the moment, though, get familiar with how this works. We'll add more detail later.

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

$

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: