30
Mon, Dec
0 New Articles

PHP for RPG Programmers: Variables, Arrays, and Functions

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

PHP makes use of variables, arrays, and functions. But can you tell them apart?

 

In my last column, we talked about some of the special operator symbols that PHP uses, which can be really confusing when you read PHP unless you're familiar with them. Remember what they were? Remember the -< operator? Really, you do? That's so sad then because there is no such operator (at least as far as I know, although I would hate to put any serious money on it; PHP operators seem to just come up out of the cracks).

No, there was the = (setting a value), == (equality of value), === (equality of value and type), && (and), and a whole lot of others. If you've forgotten, I recommend refreshing your memory quickly.

What I want to do next is to turn my attention to three entities that are crucial to PHPvariables, arrays, and functionsand help you be able to identify which is which when you see (or write) them. In this particular column, we're going to focus on variables. Arrays and functions will be covered in subsequent columns.

Variable Basics

All variables in PHP start with a dollar sign ($). The next character must be alpha or underscore, not numeric.

If you're familiar with RPG, you're used to defining the variable before you use it. You indicate the size and type of the variable right off the bat. But that's not the way it works with PHP.

In PHP, you don't formally define the variable. Instead, you define it when you move a value to it (initialize it). And the data type assigned to it will depend on the type of data that's assigned to it at that point.

Thus, $var = 1 will assign a numeric data type and a value of 1 to the variable. And $var = 'abc' will assign a string data type with a length of three and a value of 'abc'. You can even change the data type of a variable within a script simply by assigning it a new value that's a different type of data (although that's not necessarily something you want to do).

In other words, variables in PHP are loosely typed. This doesn't seem very cool to RPG people, but it is what it is. In the final analysis, it leaves proper data-type management up to the programmer. If you want to be wild and wooly, you can be. But hopefully you won't. So, to see what type of variable you're dealing with, look at what type of data it's actually carrying.

Advanced: Variable Use

Before we go on to more esoteric variable characteristics, there's something I should mention.

Those of us in the PHP world tend to think of variables as things that are used in calculations or to store values. They're simple things. X = 123. You set their value and away they go. And that's true in PHP too.

But most of the time in PHP the variable represents the result of a function. That is, in PHP we don't call functions the way we would EXSR or CALLP something in RPG. Instead, most PHP functions are "called" by being set as the value of a variable. That is, suppose in PHP we want to connect to a database. Instead of issuing a command, we use a variable like this to connect to a database:

$conn = new PDO('mysql:host=localhost; dbname=dbfile1');

Or suppose you want to open a file:

$fo = fopen('file1.txt', 'r');

You shouldn't be surprised by this; RPG has been moving in this direction for a number of years with the eval statement being used in lieu of a call, but forearmed is forewarned as they say.

Advanced: Casting and Settype

Naturally, there's a caveat here, specifically the casting and settype operators. Both of these allow you to specify the data type, but neither makes it ironclad so that it can't be overridden. PHP is just not that kind of language.

Casting is something that's done for output purposes, allowing you to change the data type of a variable so that it's more amenable for display. Say you have a variable that you have defined as text, but you want it to display on the page as floating point. (I don't know why you want to do that. I don't even know the guy. Just work with me here.) This is what casting is set up to do, and to do so you just issue this PHP command:

$var1 = '3.14'

echo (float)$var1;

What will display is 3.14 because it's now a floating point number. If you had said echo (int)$var1; then it would have shown up as 3. If you try to include this variable in a calculation after this, that won't work because it's just showing up as floating point. As far as PHP is concerned, it's still a string. Oh, and I know what you're going to ask next: What if the original value was 'abc'? What would happen when you floated it? The answer is it would show up as zero (0). It's not stupid, you know. The point is, casting doesn't change the data type of the variable, just the data type of how you display that variable.

Settype, on the other hand, actually changes the data type without having to move new data to the field. That is, you can always change the data type of a variable just by moving that sort of data to the variable, but Settype allows you to change it without doing that move. So, let's use the same example:

$var1 = '100'                       // so the variable is defined as string

$var1 = (int)$var1           // will change variable 1 so that it is integer

How important is this? Not very. What the heck are you switching data types around for? Yes, you might have to do it sometime, but most of the time you're going to define a variable's data type and then not need to screw around with it. But, if you do, this is how it's done.

Data Types Available

So what's good about PHP variables? PHP allows you to define more data types than you can in RPG, and this can be very useful in the more wide-open world of the web. Among the data types that PHP does support are:

  • StringAlphanumeric text
  • IntegerWhole numbers
  • Floating PointDecimal numbers (and extremely large integers)
  • BooleanA true or false value
  • Array A series of values, either text or numeric, where a specific entry can be referenced
  • ObjectAn object construct from OOP
  • NullAn indication that a data element is empty or non-existent. Indicates less of an existence than zero.
  • ResourceA special data type that represents a resource (generally providing a link to this resource). Yes, something like iron, or coal, something we can use to build a weapon or other sort of tool. It could be an image, a connection to a file, some sort of file handler, or another non-PHP entity. It's kind of open, you know. Resource variables aren't something you just create willy nilly; they're created by special PHP functions.

I guess I should say a word about the null data type. If you're all into SQL, then you can dig it, but the null doesn't exist in the IBM i because we deal only with the real world. Null isn't zero, and it isn't blank. Those are things that exist. A null is something that isn't really there. It's even less than low values if you know what I mean by that.

So what kind of pervert would use nulls? Turns out its very nonexistence is its strength. Sometimes, you need to decide if something exists or not. And that's where you get the null. Although we haven't talked about it yet, the predefined PHP variable $_issetor isset() functionis used to determine if something has been defined. It could be a variable or it could be an instance of something (like a database connection), but if the value of the $_isset variable is null, we know that the connection (or whatever) didn't occur (get created). Hence, when we use nulls, we're generally checking to see if a variable has been set to null. If it has, what we were trying to do has failed (because we generally issue the commands as setting a value to a variable, just the way we're starting to do when calling programs in RPG using CALLP).

Predefined Variables

So far, we've been talking just about variables that you create in your scripts. But PHP also has a whole series of predefined variables that you can use. Many of them have to do with accessing data files or dealing with the web server you're running on (remember, PHP is a server-side language, so it's not running on your PC). For a pretty complete list, look here.

Don't think you will never use these. When you get into using PHP with databases, they'll come in very handy. Just remember when you see a $_Get (for example) that it's a variable, albeit a predefined variable, not a function.

Variable Variables

This is one that you probably won't see very often, but when you do see it, it can surprise you if you're not prepared. Remember how a variable is some sort of character string preceded by a $? Well, a variable variable is a variable preceded by $. That is, if $var is a variable, then $$var is a variable variable. Consider the following code.

<?php

      $State1 = 'Alaska';

      $State2 = 'State1';

      echo($$State1);           //This will output the word 'Alaska'

?>

Of course, the question is, why would anyone want to do something like this? Hmmm, didn't really think anyone would ask me that. Give me a minute….

Actually, I may need more than a minute. Because one of the most common uses involves arrays and we haven't talked about them yet. But be patient; we'll get there. And when we do, we won't mention using variable variables. Truth is, even though you can do it, there are a lot of other things to talk about with arrays, and this one just won't make the cut. But if you see PHP code with a double dollar sign, you know you're dealing with variable variables. Check out the code, see how it's being used, and let me know. Or just keep it to yourself. Your call.

Next column, arrays. All I'll say is, in PHP, they're not your RPG's arrays.

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: