Advertisement

Object-Oriented Programming in WordPress: Functions and Attributes

by

As we continue our discussion of object-oriented programming within the context of WordPress, it's time for us to begin talking about actual features of object-oriented programming.

Though we've already covered classes, we needed to explore some foundational programming constructs before coming back around to some of the core object-oriented concepts. 

In this article, we're going to begin talking about functions and attributes: two foundational aspects of object-oriented programming. But first, make sure that you're all caught up with the previous articles:

  1. An Introduction
  2. Classes
  3. Types
  4. Control Structures: Conditional Statements
  5. Control Structures: Loops

One of the points that I'd like to reiterate about this series is that we're working on examining object-oriented programming within the context of WordPress by starting from the absolute foundational aspects of programming.

We're doing this in order to make sure that those who are beginners to programming have everything they need not only to get started with programming, but also to learn the paradigm and to eventually work into building a WordPress plugin.

With that said, let's resume our discussion by talking about functions and attributes.

Functions

For those who are familiar with procedural programming, then you are no doubt familiar with functions - after all, they're how you get work done, right?

But for those who are just jumping into programming, there are two things to understand about functions:

  1. They exist within both procedural programming, functional programming, and object-oriented programming.
  2. They can be viewed as a way to tie all of the previous constructs together to complete a more complex unit of work.

To the second point, it's true that much of what we discussed before - that is, variables, conditionals, loops, and so on - are responsible for completing a single unit work, as well; however, each of those work in conjunction with one another to achieve something slightly greater than themselves.

Depending on the language, you're also likely to hear these referred to as methods or routines. Regardless of the terminology used, the point is that functions use foundational constructs to complete an action.

Functions can work in three ways, as well:

  1. Functions can perform work by taking in information and operating on it.
  2. Functions can perform work by returning information back to the code that invoked the it.
  3. Functions can perform a unit of work without taking any information in or returning any information to the code that invoked it. Simply put, it can silently perform an action.

We'll be taking a look at each of these scenarios in more detail in just a moment, and in a future article we're going to see how they work within class. For now, let's take a look at how functions work within PHP and several nuances about each of them.

Simple Functions

Recall from the previous section that there are times in which we may define functions that don't accept any input nor do they return any information. 

In this case, these types of functions will usually perform some type of operation (such as updating an option in the database) and they will be invoked by another function after a certain operation has completed.

So, for example, let's say that we have a function that we want to use to update the underlying WordPress database. This requires that we know several things:

  • update_option
  • A key that we'll be using to store the information
  • The value to store and that will be retrieved with the key

In our case, let's say that we want to update a value in the database identified by the blog_last_updated key. Then, we'll use the PHP function time() to store the time when the function is called.

With that said, let's define our function:

<?php
function set_blog_updated() {
    update_option( 'blog_last_updated', time() );
}

Based on the description that we've provided above, you can see that the body of the function uses the update_option WordPress API function with the specified key and value that we described.

This can then be invoked by another piece of code by simply calling set_blog_updated();.

Arguments

Functions that don't accept arguments can only be useful up to a certain level. At some point, you need to be able to pass information into a function so that it can perform some type of calculation, operation, or evaluation on the information.

In keeping with our example above, let's say that we still want to update the database with a timestamp, but only if a certain key is passed into the function; otherwise, we won't do anything.

<?php
function set_blog_updated( $key ) {

    if ( 'blog_last_updated' === strtolower( $key ) ) {
        update_option( $key, time() );
    }

}

Notice that the function signature - that is, the name of the function and the data in the parentheses - has been updated to accept a variable referenced by $key.

Next, the function uses a conditional to check the value of the variable is equal to that of the key that we were looking at in the first version of the function. For the sake of making an easy comparison, it lowercases the value of $key by using PHP's strtolower function.

This means that we can invoke the function in the following way and still have it update:

  • set_blog_updated( 'BLOG_LAST_UPDATED' );
  • set_blog_updated( 'Blog_Last_Updated' );
  • set_blog_updated( 'blog_last_updated' );

All of the above function calls will perform the following operation; however, if we were to pass anything else into the function, the conditional would evaluate to false and would not fire the update function.

For example, calling set_blog_updated( 'not_now' ); would not work.

Returns

Now, let's say that we want the function with which we're working to return a value. Specifically, let's say that we wanted to return a value on whether or not the update function fired successfully. 

To do this, we can take advantage of a function's return statement as well as the value that the update_option function returns. According to the WordPress Codex, update_option will return the following:

True if option value has changed, false if not or if update failed.

To that end, we can adjust our function to work like this:

<?php
function set_blog_last_updated( $key ) {
    
    $was_updated = false;
    
    if ( 'blog_last_updated' === strtolower( $key ) ) {
        $was_updated = update_option( $key, time() );
    }
    
    return $was_updated;
    
}

Now we have a function that accepts an argument, returns a value, and also leverages a conditional not only to update the value but also to make sure the value was updated successfully.

Given the function above, we can invoke it like we have in previous examples, but now we can store it's result in a variable that will allow us to further improve the code in our program.

For example, we can continue to call the function by saying set_blog_last_updated( 'blog_last_updated' ); but now we can also store the result of the function in a variable.

To do this, all we need to do is write a line of code that performs the following: $blog_was_updated = set_blog_last_updated( 'blog_last_updated'); In this case, the variable $blog_was_updated will be set to true if the condition ran and the update call was successful, but will be false if the condition did not run or if it did run but the update_function failed.

Variable-Length Arguments

There's one other aspect of functions that are beyond the scope of this particular article and that is variable-length arguments. In short, there's a way that a function can accept a number of arguments that we aren't able to anticipate while writing code.

 If you're interested in reading ahead, then you can check out the article in the PHP manual; however, we'll look to cover this later in the series.

Attributes

At this point, we're going to shift gears and talk about something that's purely related to object-oriented programming and that's class attributes.

Recall from our discussion on classes that we looked at a sample class for a Blog_Post. For reference, the code looked like this:

class Blog_Post {
 
    private $author;
     
    private $publish_date;
     
    private $is_published;
     
    public function publish() {
        // Publish the article here
    }
     
    public function delete() {
        // Delete the article here
    }
 
}

At this point in the series, you should be able to easily identify the class definition, the function definition, and the attributes.

Specifically, the attributes are the three variables that exist at the top of the file above the functions. As stated in the article on classes, attributes can be thought of as the adjectives that describe the class.

In the example above, we have a class that represents a blog post, and a blog post can be described by its author, its publish date, and whether or not it has been published.

These particular values are nothing but variables as we've looked at earlier in the series, and they can hold any type of value be it a primitive data type such as a string, integer, boolean or it can reference a more complex data type such as an array or another object.

The point of attributes is that they exist at the class level. This means that the variables can be used in any of the functions that are defined in the class - they don't have to be passed as function arguments, and they can be updated to to reflect the state of the object at any point during its runtime. 

Now, in terms of how they are set, this is done within the context of a special type of function called a constructor. In short, a constructor is a function that is set aside specifically for initializing a class, and in many cases, it's used to initiate values.

In PHP, a constructor is a function that is named __construct which is a reserved word in the language. So given the attributes above and our primer on functions, here is how we might go about initializing our attributes:

class Blog_Post {
 
    private $author;
     
    private $publish_date;
     
    private $is_published;
    
    public function __construct() {
    
        $this->author = '';
        $this->publish_date = null;
        $this->is_published = false;
    
    }
     
    public function publish() {
        // Publish the article here
    }
     
    public function delete() {
        // Delete the article here
    }
 
}

One of the most important things to take away from the above code is that attributes are references slightly differently than normal variables. Specifically, notice that they are referenced using the $this keyword. This is what differentiates attributes from normal variables within a class definition.

Secondly, note that the variables that are being set to initial values. As it stands right now, each blog post that is created will not have an author that is specified, it will not have a publish date, and it will not have a state of being published.

As we get further into discussing object-oriented programming, we're going to talk about how variables are set, how they can be used throughout the class, how they can be set, retrieved, and so on.

Public, Private, and What?

For those astute readers, you've likely noticed the keywords being used throughout the code such as public and private. There's also another keyword that is used within object-oriented programming and that's protected.

We'll talk about each of these in detail in the next article.

Coming Up Next

As we just mentioned, there are a number of keywords that are used to refer to attributes and functions all of which have to do with what's known as scope. In the next article, we're going to begin exploring variable and function scope which is a core idea in object-oriented programming.

So as we've covered all of the foundational elements of programming in PHP, we're now getting ready to move more into object-oriented programming after which we'll be moving into applying the concepts and techniques in WordPress development.

Advertisement