For those of you who have been following along with the series thus far, then you know we are taking a look at object-oriented programming specifically from the perspective of a beginner.
This means that we're approaching the topic not only for those who are looking at how to get started with the paradigm, but we're looking at all of the various features of PHP that make up the language and that are ultimately used within the context of object-oriented programming.
Additionally, we're doing all of this within the context of WordPress so that, by the end of the series, we can see how a practical application of how all of this can be used within a real world example.
If this is your first time reading an article in the series, then I highly recommend checking out the previous articles as each article in this series builds on the one before it.
So far, we've covered the following:
In this article, we're going to be talking about control structures.
What Are Control Structures?
"Control Structures" is a fancy term term that describes how we can, ahem, control how the code flows through our program based a number of factors.
For example, let's say that we want to progress through a certain set of instructions, but you want to do something if one variable is set, or another set of instructions of another variable is set.
Or let's say that you have a set of data that you want to loop through reading each value, setting each certain values, or even creating certain values.
Whatever the case may be, the way that you go about doing this is through the use of control structures. In the remainder of this article, we're going to be covering two types of control structures: Conditionals and Loops.
Though conditionals and loops are the types of control structures that we're going to be reviewing, there are subsets of each.
For example, conditionals have:
-
if/then
statements -
switch/case
statements
Loops, on the other hand, have a few other variations:
for
foreach
do
while
Though these may be new constructs for some of you, we've already covered the basics in the previous articles, so we have everything that we need to move forward.
Conditional Statements
In my opinion, conditional statements are some of the easiest to understand as they read more like sentences than many other types of programming statements. For example, if you're literally saying "if this condition is true, then do this action; otherwise, do this action."
Sure, it gets a little more complicated than that if you have, say, a few other conditions to check before deciding on a course of action, but the gist of it remains the same.
So with that said, let's start by taking a look at one of the two variations of conditionals that are offered by PHP.
if/then
Statements
As previously mentioned, the most basic conditional statement is of the form if/else
, and you'll generally see it written like this:
<?php if ( condition ) { // Take on action } else { // Take another action }
Of course, this still doesn't really explain how the control structure works, does it? I mean, Sure, it provides a bit of a skeleton for how to take a look at it, but it leaves more to be desired.
Namely, what is this condition line? Secondly, what are courses of action that the control structure can take?
First, the condition refers to any statement that can be evaluated as a boolean expression. Make sense? Simply put, condition represents any statement that can be evaluated as true
or false
.
So, for example, let's say that we have two values:
$is_active
$total_count
These are obviously somewhat generic values, but let's say that if $is_active
is set to true, then we'll increment the $total_count
by one; otherwise, we'll subtract the $total_count
by one.
This is how it may look in code:
<?php $is_active = true; if ( $is_active ) { $total_count = $total_count + 1; } else { $total_count = $total_count - 1; }
In the above example, $total_count
will be increased by one because $is_active
evaluates to true.
Alternatively, let's say $is_active
is set to false
.
<?php $is_active = false; if ( $is_active ) { $total_count = $total_count + 1; } else { $total_count = $total_count - 1; }
In this example, $total_count
will be decreased by one because $is_active
evaluates to false.
Now, before we look at the next example, it's important to understand that these are extremely trivial examples. The purpose of these examples is not to showcase how to take complex operations and to combine them into the conditional constructs, but instead how to use the conditional constructs.
When we get to the part of the series that has us beginning to write a plugin, then you'll see how we can use more elaborate expressions within a practical application.
With that said, let's look at one more examples of if/then statements. In this example, we'll take a look at if/elseif/else
. To get started, let's assume that $is_active
is set to true and $total_count
is set to 10.
<?php $is_active = false; $total_count = 10; if ( $is_active ) { $total_count = 1; } else if ( $total_count >= 10 ) { $total_count = $total_count + 1 } else { $total_count = $total_count - 1; }
The above code can be read like this:
- If
$is_active
is set to true, then set the$total_count
to one.$is_active
is not true. - Otherwise, if the
$total_count
is greater than or equal to 10, then increment the$total_count
by 1. The$total_count
is equal to 10, so we'll increment the$total_count
to 11. - If
$total_count
was not greater than or equal to 10, then we'd decrement the$total_count
by one.
By the time the block of code finishes executing in the above example, $total_count
will be equal to 11.
Make sense?
This is why we call these control structures: These statements (or evaluations) allow us to determine what code to run based on certain conditions.
For those who have been programming for a while, you're familiar with more complex expressions using operators such as &&
and ||
and so on. We'll eventually get to that, but not in this article.
All that say, it's a topic I'm aware of and that we'll cover, but not today.
Anything Else?
For those of you who are more experienced with programming, then you're likely familiar with the ternary operator.
We're not going to be taking a look at that in this particular series of articles as it's outside the scope of what we're looking to cover; however, if you're feeling adventurous and are looking for a more concise way to write a simple if/else
statements, then checkout the ternary operator in the PHP manual.
switch/case
Statements
With that said, there's one more type of conditional that we need to take a look at before moving on to the next topic.
This particular construct still falls under conditional statements; however, I'd argue that you'd see it used less frequently than its if/else
counterpart.
As the title denotes, this is called the switch/case
statement. Though I personally think that the language makes it a little more convoluted to follow, the way in which control flows through the evaluations isn't much different from what we've already seen.
Like we did with the if/else
statements, let's first look at how the switch/case
is structured and then we'll take a look at a couple of trivial examples.
<?php switch ( condition ) { case 'value': // do action break; case 'another value': // do a different action break; default: // perform a default action break; }
The first thing to note about this particular type of conditional, is that the evaluate happens in a single place: at the top of the block of code right next to the switch
statement.
Here, the evaluation happens once and then each of the subsequent case
statements is what dictates which action is taken. There is also a break
statement included with each of the statements that we'll discuss, and there is also a default
block of code at the bottom that we'll discuss by the end of the article, as well.
But before we do any of that, let's setup a slightly more practical example of what a basic switch/case
statement looks like.
Let's assume that we have a value, $first_name
, and then we want to take a certain course of action based on the person's first name. In this example, we'll set a person's email address based on their first name. If we don't recognize the person's first name, then we'll set the value equal to null
.
Sure, it's a bit of a contrived example, but it will demonstrate the point:
<?php $persons_name = 'Tom'; $email_address = ''; switch ( $persons_name ) { case 'Tom': $email_address = '[email protected]'; break; case 'David': $email_address = '[email protected]'; break; default: $email_address = NULL; break; }
Let's look at the flow of control in the above example:
- We define a
$persons_name
as 'Tom' and we initialize the$email_address
as an empty string. - We then pass the
$persons_name
to the switch statement for evaluation. - The control structure will evaluate the
$persons_name
against each value specified in the case statement. - Since 'Tom' is the value of the
$persons_name
, then the$email_address
will be set to '[email protected]'
If we were to pass 'David' as the $persons_name
then $email_address
would be set to '[email protected]'.
Next, if we were to pass any other name than 'Tom' or 'David', then the $email_address
would be set to NULL
. It's also important to note that switch/case
is case sensitive. This means that if you were to pass 'tom' instead of 'Tom', then they would be treated as different cases.
Finally, note that each case
ends with a break
statement. This is important because break
instructs the code to hop out of the switch/case
statement and continue working on whatever code comes next.
It's extremely important to understand that if you forget a break statement, then it will immediately fall down to the next case statement which can obviously have erratic results (such as setting the wrong $email_address
).
One example to where you can leverage this to your advantage is like this:
<?php $persons_name = 'Tom'; $email_address = ''; switch ( $persons_name ) { case 'tom': case 'Tom': $email_address = '[email protected]'; break; case 'David': $email_address = '[email protected]'; break; default: $email_address = NULL; break; }
In the above example, we've defined cases for both 'Tom' when it's lowercase or has the first letter capitalized and demonstrates how the code will fall through to the next case
statement.
But there's an even better way to make this more bulletproof:
<?php $persons_name = 'Tom'; $email_address = ''; switch ( strtolower( $persons_name ) ) { case 'tom': $email_address = '[email protected]'; break; case 'david': $email_address = '[email protected]'; break; default: $email_address = NULL; break; }
Notice that this takes the PHP function strtolower
in order to force the incoming $persons_name
to be completely lowercased. This allows us to refine our case statements even more.
What's Up Next?
In this article, we looked at the first of two groups of control structures that are available to us in PHP. No, these are not explicitly part of object-oriented programming, but before we actually get to talking about more fundamentals aspects of the paradigm, we need to understand all of the finer points that allow us to write object-oriented code.
To that end, we're going to continue this discussion on control structures in the next article by looking at loops.
After that, we'll be ready to turn our attention to functions. For those who are familiar with procedural programming, then functions are nothing new; however, if you're new to object-oriented programming, then there are a number of factors that differentiate them from how they are used in procedural programming.
So that's the roadmap for the next set of articles. As usual, feedback is always welcome and I look forward to continuing our discussion in the next article.
Comments