02
Sat, Nov
2 New Articles

PHP: Variables, Arrays, and Functions: The Final Chapter

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

This is the last step in understanding how variables, arrays, and functions are similar, are different, and come together to form the basis of the PHP universe.

 

So far in this series, we have covered variables and arrays. Granted, it took us three months to cover arrays and how to display them, but let's not worry about that now.

 

In the process, we saw that variables were preceded by a dollar sign ($) and consisted of underscores plus any alphanumeric digits (that is, no special characters) as long as the first character after the $ was an underscore or alpha. We saw that we did not have to specify what the data type was or what the field looked like. Instead, that was determined by the type of data we put in that variable. And speaking of data types, we saw that a PHP variable could be an integer, string, floating point, object, resource, Boolean, or array.

 

And speaking of arrays, we saw that an array is a variable (so it starts with a $) and that there are really two types of arrays: numeric and associative.

 

Numeric arrays are the kind of array that we are most familiar with in RPG. That is, they have a numeric index, and the difference between RPG and PHP is that the index in RPG starts with 1, and in PHP (which is derived from C) it starts with 0.

 

The second type of array is the associative array. In this case, we can make the index not just a number but a string. That means we can have an array in which the index is 'name', 'Address1', 'City', etc. Obviously, this gives us a whole new dimension and allows us to keep file-like structures within the PHP script, which is very useful when reading records from a website or writing records to it. We saw that this process (using the foreach operator) was not trivial but neither was it rocket science.

 

There is one more entity that we should look at to round out all of this stuff, however, and that is functions.

Functions

In one sense, a function is like an RPG subroutine. Although to be honest, it is actually much more like an RPG subprocedure. What's the difference? A number of things, of course, but the one I'm talking about mostly is how they each handle variable scope. Subroutines have no concept of variable scope. There are no local variables; everything is a global variable. But subprocedures have local and global variables. Hang on to that thought; we'll return to it eventually.

 

Functions in PHP are a way of packaging capability, sometimes one function but generally more than one into a neat little package that can be run as a unit. By themselves, functions are not object-oriented, but they're important building block of the classes that do define OO.

 

Function names are not preceded by a $ (or any special character) like variables are, but they do consist of alphanumerics and underscores. Certain special functions, ones that are a default part of PHP, start with two underscores and are called "magic methods." But most of the functions you use will be ones that you define yourself. Probably. Actually, I have no idea what kinds of things you're likely to do in the future. No clue. But that's not my problem, so let's just move on.

Defining Functions

You will remember that we defined variables by simply assigning a value to the name, such as $name = 'Dave';. Functions, on the other hand, are defined by using the special "function" keyword.

 

Function Write_Msg()   {

       echo "Write a Message";

}

 

Let's dissect this. "Function" is the keyword that lets PHP know you're creating a function. Duh. Write_Msg is the name of the function. The parentheses are required; later we'll stick some parameters in there. Finally, the braces are also required; they enclose the statements that are to be carried out when we run the function. In this case, all we're going to do is display the message Write a Message on the screen. Also, please note that there's a semicolon after each of the statements enclosed in braces, but none, that's right, none at the end of the function definition.

Calling or Running a Function

So if that's how to define a function, how do you get it to run? Simple.

 

Write_Msg();

 

That's right. That's all there is to it. If you ran this function by calling the URL for the script that contains the function definition, the following would display on the web page.

 

Write a Message

 

What I'm saying is that if you wrote and ran the following script,

 

<?php

Function Write_Msg()     {

echo "Write a Message";

}

 

Write_Msg();

?>

 

you would see Write a Message displayed on the web page.

Functions with Parameters

In the above example, we didn't put anything in the parentheses when we defined the function. But you could put parameters in there and pass them into the function.

 

<?php

Function Add($num1, $num2)  {

$sum = $num1 + $num2;

echo $sum;

}

 

$num1 = 3;

$num2 = 5;

 

Add($num1, $num2);

?>

 

The above script defines the Add function, sets the initial values of the two parms, and then carries out the add and display that are part of the function definition. If you run this script, you'll get the result of 8. Notice that you don't need to define the variables before you use them as parameters, but you must set values before you run the function.

 

I would be remiss if I didn't point out that in the wild (that is, in most of the PHP programs you will see), the function is executed by setting it equal to a variable, just like the way we can call programs in /free by using an eval statement. So, the above could be written as

 

$ans = Add($num1, $num2);

echo $ans;

 

and the result of 8 would be displayed. Note that $ans isn't defined anywhere previously; it just sort of creates itself out of nothing, much like xxx.

Variable Scope

One of the big lessons we can take out of this is to learn something about variable scope. If you're doing just regular RPG, then all of the variables in a program are global variables. Doesn't matter if they're used in just one subroutine or not; they're global variables that are defined in F- or D-specs at the start of the program.

 

If, however, you're using subprocedures in your RPG program, you know that you can also define local variables (using D-specs within the subprocedure) that are valid in the subprocedure but are not available in the rest of the program.

 

PHP also has both global and local variables, and you're really encouraged in PHP to use local variables, not global. This becomes easier in OO PHP, where you can define classes consisting of both variables and functions, but it's a good idea for procedural PHP also.

 

For example, if we have this script

 

<?php

 

$num1 = 3;

$num2 = 5;

 

Function Add()   {

$sum = $num1 + $num2;

echo $sum;

}

 

Add();

 

?>

 

we would get a result of 0 rather than 8. Why? Because the variables in this script are global variables; they're defined outside of the function, and hence they don't work in the function.

 

And this is one of the purposes of the parameters. If we instead write the function as

 

Function Add($num1, $num2) {

$sum = $num1 + $num2;

echo $sum;

}

 

Add($num1, $num2);

 

then the result would be 8. The use of parms would allow us to bring the global variables in and use them in the function (as we did above).

Summary

So is that it? Are functions really that simple? Well, yes, sort of. Remember, the real complexity of the function is the set of statements that you put in it. But there's more to learn about functions: setting up default parms, passing parms by reference or value, using dynamic function names, etc. But I will leave that up to you. Take care.

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: