Like many WordPress developers, the first time I wrote PHP, I didn’t know anything about PHP or software development in general. As I started to tackle more advanced concepts, however, I struggled because I never learned the fundamentals of PHP that were assumed in the materials I encountered.

Regardless of your stage in your process of learning PHP as a WordPress developer it’s important to make sure you know the basics. In this article, I will discuss PHP fundamentals: variables, constants, data types, functions, and scope.

This knowledge will equip you to learn PHP and other languages, as most of these concepts are fundamental to software development in general.

Variables and Constants

The most simple “hello world” PHP program looks like this:

echo 'Hi Roy';

This prints the words, “Hi Roy.” But as our program grows, we might want to print these words more than once, or use conditional logic to decide when or where to print them.

While in principle we could just cut and paste those lines of code into multiple locations,  it directly violates the “Don’t Repeat Yourself” (DRY) principle, one of the most sacred principles in software development. To avoid this, store the words “Hi Roy” into a variable before expanding the program, like this:

$hi = "Hi Roy";

echo $hi;

Now we can reuse this variable to change its value:

$hi = 'Hi Roy';

echo $hi;

$hi = 'Hi Shawn';

echo $hi;

In software development, a variable is a value that changes based on the conditions or information passed to the program. When you create a variable and put data in it, that data now exists somewhere on the server as a unique value in RAM.

Like variables, constants are another item in which content can be stored. As the name suggests, as opposed to variables — whose values can vary during a request — the content of constants can not.

For example, here is a constant we define in our wp-config.php:

define( 'WP_DEBUG', true );

If I tried to define WP_DEBUG anywhere else on my site, I would get an error because constants never change. That’s why we tend to use them less frequently than variables and primarily in program configuration.

Data Types

In the previous section, I used two different types of data to set the value of constants and strings. I used strings for the variable and a boolean for the constant. Strings, which contain combinations of letters, numbers, and other characters and booleans, which can be either true or false are two of PHP’s eight different data types.

It’s important to note that PHP is a “dynamically typed language,” which means that a variable can change its type. This is not true in many other languages. An upside to this is that we have more flexibility, but we also have to be make sure the variable is the type we expect it to be before using it.

PHP is also very flexible. For example, PHP is not concerned about the difference between a string that holds a number and a variable of the integer — i.e., number — data type. For example, this will work totally fine:

$one = 1;

$three = '3';

$four = $one + $three;

We have four simple data types: strings, integers, booleans, and floats. Floats differ from integers in that they can have decimal values, where integers must be whole numbers. These simple data types only contain one value. There are, however, two “compound” data types — arrays and objects — which can contain more than one value and those values can be of any data type.

We create arrays using the function array() or bracket notation. The latter option was added in PHP 5.4. I prefer the bracket notation, but have to be mindful of the backwards compatibility issues because most WordPress sites run an obsolete version of PHP.

Arrays are structured representations of multiple pieces of data, which can be written like this:

$post_titles = [
    '10 Things You Always Wanted To Know About Coffee',
    '8 Worthless Facts About Coffee',
    '5 Things That Would Matter Except You Need More Coffee'

This is a simple, one-dimensional array, which means  it has only one level of depth. Arrays can gain depth by nesting other arrays within them, like this:

$posts = [
    'drinks' => [
        'coffee' => [
            '10 Things You Always Wanted To Know About Coffee',
            '8 Worthless Facts About Coffee',
            '5 Things That Would Matter Except You Need More Coffee'
        'tea' => [
            'Tea and Other Alternative Caffeine Delivery Systems?',
            'Decaf Tea: As Opposed To Coffee, This Is A Good Thing',
    'foods' => [
        '9 Tasty Vegan BBQ Solutions',
        '5 Sandwiches of Epic Victory'

We would call this a multidimensional array because of its nested structure.

Some arrays also have “keys”. We could access the food “key” like this:

$food = $post_titles[ 'food' ];

Nested keys, like the coffee key, which is nested under drinks, must be accessed using that hierarchy. For example, this would generate a warning:

$coffee = $post_titles[ 'coffee' ];

However, this would work:

$coffee = $post_titles[ 'drinks' ][ 'coffee' ];

Note that if we do not specify keys, then PHP indexes the array using numbers, starting with zero. So to get the second entry in the coffee array we would use the number one like this:

$title = $post_titles[ 'drinks' ][ 'coffee' ][1];

Arrays are mutable. That means that we can change their contents at any time. For example, we could add another item to the array like this:

$post_titles[] = '8 Fun Facts About Juice';

The entry in the array would get pushed onto the end and numerically indexed, which doesn’t make much sense with our structure. It would be better to define a key for juice and place it there:

$post_titles[ 'juice' ][] = '8 Fun Facts About Juice';

Functions and Scope

As I mentioned before, part of the reason to have variables is to avoid writing repetitive code that violates the DRY principle. While variables are containers for information, functions are containers for functionality. If we need to do something, we almost always want to encapsulate that functionality in a function.

I’m going to discuss functions and scope together now. This is necessary as functions separate code from the rest of the program.

Doing so not only keeps things DRY, but also makes that functionality available throughout the program and lets us run it as many times as we need.

Functions in PHP are created using the “function” keyword, followed by a name for the function and parenthesis, which might contain function arguments. Function arguments are how we pass information into a function.

Inside of a function, there are only variables passed in as arguments. Variables defined outside of that function are not accessible. They are considered outside the “scope.”

Let’s consider this function, called slug_get_product:

function slug_get_product( $slug ){
    return get_post( [ 'post_type' => 'my-product', 'post_name' => $slug ] );

This function is basically a wrapper for WordPress’ function get_post(). It gets a post with a specific slug in the post type “my-product”. Having one utility function for this saves having to write the same argument set for get_posts() multiple times. It also means that if you change the name of that post type, there is only one line of code to change.

Note that we passed in the variable $slug as an argument. That’s why we could use $slug inside of the function. On the other hand, this wouldn’t work:

$slug = 'red-shoes';
function slug_get_product( ){
    return get_post( [ 'post_type' => 'my-product', 'post_name' => $slug ] );

The reason this doesn’t work is that inside the function we are trying to use a variable called slug but in that scope no such variable exists. Even though one of that same name does exist, it is in a different scope and therefore can not be accessed.

In fact, we could write code like this with two variables named $slug, but because one is inside the function and one is not they are two totally different variables with totally different values:

$slug = 'red-shoes';
function slug_get_product( ){
    $slug = 'blue-shoes';
    return get_post( [ 'post_type' => 'my-product', 'post_name' => $slug ] );

This may seem complicated as it looks like they are the same variable because they both have the same name. That’s a coincidence. They are in different scopes and are therefore totally different. Despite having the same name, they represent a different configuration of transistors in your server’s RAM.

By the way, notice how I added the prefix “slug” to the function names? That’s because there can only ever be one function in a program with the same name. Adding a second function of the same name generates a fatal error.

This is why you should always prefix your functions with a unique prefix that is consistent throughout your plugin or theme. When you see articles like this use a prefix like “slug,” which means you should change “slug” to your own prefix.

So far scope has been limited to inside a function and outside of it. We also have what is called global scope. Like its name suggests, global scope is available everywhere. Constants are in global scope and can be accessed anywhere.

Variables can be placed in global scope or accessed from global keyword. Global scope should be avoided as much as possible. WordPress uses a lot of global variables. This is mainly because it was originally written in PHP 4 and there was no other way to solve the problems global variables solved.

WordPress’ use of global variables, while not wonderful, is ultimately not that bad as it is the core application that plugins and themes work with. Plugins and themes, for the most part, should not add variables to the global scope.

Still, as a WordPress developer, you need to understand global scope. Inside of the WordPress loop, the current post is stored in a global variable called post. So if you had a function that ran inside of the loop, to access the current post, you would do this:

global $post;

In general it is better to use functions like get_post() or get_the_ID() that do that for you. The more you avoid accessing global variables or seeing them as ways to share data between functions, instead of passing that data in as an argument, the better.

Is That It?

That’s a good start to the basics of PHP for WordPress development, but you still have a lot to learn. I hope by reading this article, you are better equipped to read coding tutorials and to work with code you find online. More importantly you should be able to understand decisions in code you read better and how to work with it.

Next, I’d recommend looking at control structures — loops and conditionals — as well as classes and objects.

Josh is a WordPress plugin developer and educator. He is the owner and a developer for CalderaWP, makers of Caldera Forms, a different kind of and the native WordPress A/B testing solution.

The post PHP Fundamentals For WordPress Developers appeared first on Torque.

Share This