PHP 7 | Torque All the Word that's fit to Press Wed, 15 Dec 2021 19:21:55 +0000 en-US hourly 1 https://wordpress.org/?v=6.6.1 Torque Toons: European Day Of Languages 2018 https://torquemag.io/2018/09/torque-toons-european-day-of-languages-2018/ Wed, 26 Sep 2018 17:34:34 +0000 https://torquemag.io/?p=85246 Parlez-vous JavaScript? Let’s celebrate #EDL2018. Don’t forget to check out our other editorial toons!

The post Torque Toons: European Day Of Languages 2018 appeared first on Torque.

]]>
Parlez-vous JavaScript? Let’s celebrate #EDL2018.


Don’t forget to check out our other editorial toons!

The post Torque Toons: European Day Of Languages 2018 appeared first on Torque.

]]>
Torque Toons: Back to School for WordPressers https://torquemag.io/2018/09/torque-toons-back-to-school-for-wordpressers/ Wed, 19 Sep 2018 21:58:34 +0000 https://torquemag.io/?p=85206 It’s back to school season. Time to hit the books and start learning PHP 7. Don’t forget to check out our other editorial toons!

The post Torque Toons: Back to School for WordPressers appeared first on Torque.

]]>
It’s back to school season. Time to hit the books and start learning PHP 7.

Don’t forget to check out our other editorial toons!

The post Torque Toons: Back to School for WordPressers appeared first on Torque.

]]>
How to Easily Check and Update the PHP Version of Your WordPress Site https://torquemag.io/2018/01/update-php-version-wordpress/ https://torquemag.io/2018/01/update-php-version-wordpress/#comments Tue, 09 Jan 2018 17:43:28 +0000 https://torquemag.io/?p=83159 All websites are running on code. In the old days, it was pure HTML, today it’s usually a mix of that plus CSS and JavaScript. However, that’s only once they are loaded. On the server, a different programming language is likely running the scene, especially if you have a WordPress website. We are, of course, talking about PHP. Most of the things you see on both the front and back end of your WordPress site exist thanks to PHP. You don’t only find it in your page templates, it also makes up the files that build the WordPress dashboard. The […]

The post How to Easily Check and Update the PHP Version of Your WordPress Site appeared first on Torque.

]]>
All websites are running on code. In the old days, it was pure HTML, today it’s usually a mix of that plus CSS and JavaScript.

However, that’s only once they are loaded. On the server, a different programming language is likely running the scene, especially if you have a WordPress website. We are, of course, talking about PHP.

Most of the things you see on both the front and back end of your WordPress site exist thanks to PHP. You don’t only find it in your page templates, it also makes up the files that build the WordPress dashboard.

php code in wordpress dashboard file

The same is true for any themes and plugins you may have installed. In short, without PHP your WordPress website would not exist.

Because this programming language is so central to the WordPress platform, today we want to talk about something that many of us deal with too rarely: how to update the PHP version of your site.

What, you didn’t know that was even part of running a website? That’s exactly why this post exists. In it you will learn a little more about PHP as a language and why it’s important to run the latest version, how to check your site’s PHP and how to upgrade it safely.

Ready to get a little nerdy? Then let’s dive right into it.

Table of Contents

  1. A Short Overview of PHP as a Programming Language
  2. Why Update the PHP Version of Your WordPress Site?
  3. How to Check Your WordPress Site’s PHP Version?
  4. How to Upgrade PHP Safely
  5. Summing Up

A Short Overview of PHP as a Programming Language

Just so you know what we are talking about, let’s first dive into what PHP is exactly.

First of all, it’s a programming language that is open source and thus (like WordPress) free to use. That might also contribute to the fact that PHP is one of the most popular languages for web development. It not only runs the scenes behind WordPress but is also a part of Facebook and other popular sites. However, you can use it for other purposes as well.

A second important thing about PHP is that it’s a server-side programming language. That means, it is processed on the machine whose hard drive it lies on. That is opposed to client-side languages like JavaScript, where all the work happens in the browser of the person requesting to see your site.

However, that also means that any problems with site performance that stem from PHP are yours to fix. Your visitors can have the fastest computer in the world, however, if your server is low on resources, that’s not gonna make much of a difference. Which brings us to the next part.

Why Update the PHP Version of Your WordPress Site?

Because PHP is so important to WordPress, it’s also a central part of site performance. After all, PHP is basically the middle man pulls the correct data from your database, wraps it in HTML and CSS and then delivers it as a finished site to the visitor’s browser. If the middleman is slow, so is everything else.

PHP Updates Mean Improvements

For that reason, the programming language is constantly being improved upon. It has seen quite a bunch of versions throughout the years.

To run WordPress, your server needs at least PHP 5.2.4. However, by now the official recommendation is that you run PHP 7.4 or higher (the current version is PHP 8).

That’s because, just like WordPress, new versions of PHP bring a lot of improvements with them. As it progresses, the languages gets more secure, faster, leaner, less resource hungry and just overall better. In fact, just the jump from PHP 5.6 to PHP 7 was a great leap forward.

PHP 8 is the Best One Yet

It may not be the monster of an update PHP 7.0-7.4 was, but PHP 8 has a lot to offer. Sorting through all that documentation and puzzling out the most important features can be difficult, so we’ve gathered it all here for you.

Though it may not be super groundbreaking, PHP 8 has several important features you’ll want to get ready for. The JIT compiler opens up new horizons for the language. On a smaller scale, the new attributes, match expression, and functions will be very useful for plenty of developers. And, of course, union types and named arguments.

Watch out for the breaking changes, but overall this update is fairly light on the major backwards-incompatible features.

See an in-depth dive into the newest features here.

Older Versions of PHP are No Longer Supported

In addition to the above, the lifetime of older PHP versions is running out. Active support for version 7.4 ended December 2020. Security support will only be provided until December 21, 2021.

Convinced yet? And those are just the cliff notes. There’s more awesome stuff that has improved in PHP 8 that you can learn about here. However, how do you figure out which PHP version your site is currently running on? I’m glad you asked.

How to Check Your WordPress Site’s PHP Version

If you want to know which version of PHP currently powers your WordPress site, you have several ways to find out. Let’s go over them real quick.

1. Check Your Hosting Management Panel

Your first option is to check with your provider. In the back end of your hosting account, there’s likely a menu called PHP Settings, PHP Version Manager or something similar. From here, you can check which PHP version your site(s) are using.

Most often you are also able to upgrade to another version here (more on that below) and do things like edit PHP.ini. The latter is an important file that allows you to make changes to server functionality.

2. Use a WordPress Plugin

Of course, in the WordPress ecosphere, you also have plugins that can do the same for you. One of the easiest to use is Display PHP Version.

Pretty much all you have to do is install the plugin and activate it. You will then be able to see the current PHP version under At a Glance in the WordPress dashboard.

display php version wordpress plugin

If it turns out that your server is already running the latest version, there’s nothing to do but smile happily and move on with your day (or maybe send your provider’s sysadmins a box of chocolates).

However, if you have never dealt with this issue before, chances are good that the PHP version is not up to date. In that case, we will show you how to upgrade it safely in the following.

Of course, that requires that your provider offers the option to switch. If not, maybe it’s time to find new hosting?

How to Upgrade PHP Safely

As cool as PHP 8 is, there are some risks involved with upgrading. That mostly means the possibility that you have code on your site (meaning in WordPress core, themes, plugins, and scripts) that is not compatible with the new version.

If that is the case, when you make the switch, all or parts of your site might break or at least show faulty behavior. That’s why it’s important to check this kind of thing beforehand and we will show you how below.

Quick note: the process laid out here is how to upgrade your live site. However, an even better idea is to create a local copy of your site and run through it once on your computer. That way, you reduce the chance of running into any nasty surprises even further.

1. Back Up and Update Everything

As mentioned, problems with upgrading PHP usually stem from older code that is no longer compatible with the newest version. The best solution: upgrade your site.

The WordPress community is a strong advocate for using the latest version of PHP. For that reason, core, plugin, and theme developers make sure their work jive with it.

Consequently, the first step to make sure your site doesn’t produce problems is to keep your site up to date. That’s something you should do either way for security reasons.

So, back up your site and then click the upgrade button wherever necessary. Do it now, I’ll wait.

2. Use a Plugin to Check for PHP Compatibility Issues

Done? Cool, then let’s continue.

Even with up-to-date WordPress and extensions, there is no guarantee that everything will go over smoothly. Thankfully, you don’t have to just have to hope for the best. Instead, you can test for incompatibility issues beforehand. How? With a plugin of course.

WP Engine has released a free plugin in the WordPress directory, for just this purpose. It checks all the code on your site and reports any possible issues.

To use PHP the compatibility plugin, you first have to install it on your site in the usual way. When it’s active, there will be a new menu item under Tools called PHP Compatibility. Here, just choose the PHP version you want to upgrade to. Then select whether to scan only your active plugins and themes or all extensions on your site.

update php version safely with php compatibility checker

Start the scan. When done, the plugin will present you with a list of errors and warnings for your site. It will even tell you the file name and line number where it encountered them.

From here, you can take action to replace faulty plugins or themes or find a different kind of solution (such as asking the developer to update their work). The plugin will also make suggestions.

By the way, if you have a plugin that is up to date but still flagged as incompatible, it might also be a false positive. WP Engine provides a list of plugins known to be flagged for compatibility issues when there aren’t any. So, take that into account.

3. Upgrade Your Version of PHP

Once you have made sure that your site is, by all accounts, able to handle the switch, it’s time to actually make it.

There are several ways of doing that. One is via SSH commands. However, if you know how to do this, you are probably not reading this article. Consequently, we won’t be going over it. However, if you still want to learn about upgrading your server’s PHP version via SSH, you can do so here.

We will go the easier way, which is to update your WordPress PHP version via the admin dashboard of your hosting provider. For example, in cPanel (which, by the way, is also based on PHP) it’s as easy as finding the menu item PHP Version Manager, navigating to your site’s location, picking the version you want to change to and hitting Save.

upgrade php version in cpanel
Source: SiteGround

If your host is running Plesk, you can find out how to upgrade PHP here. Unfortunately, for other admin panels, you will have to do your own search. Should you be unable to find any such option, your host might have disabled it. In that case, you need to get in touch with your provider.

4. Check Your Site

Once you have upgraded, the last thing to do is go back to your site’s front end and have a look around. Check every page to see if everything looks as it should and that parts of your site aren’t disabled or similar. Also, test the plugins you are using as well as theme features. However, if you have taken the precautions mentioned above, it’s very unlikely that there was a problem.

And that’s it. Congratulations! You just successfully upgraded PHP for your WordPress site.

Summing Up

PHP is the glue that holds WordPress together. For that reason, it’s important to keep it up to date. This will also allow you to profit from increased speed and security.

Above, you have learned about PHP and why it is important to upgrade. We have talked about how you can find out which version your site is running and how to prepare it for updating. Plus, we have told you how to implement said upgrade via your hosting management panel.

If you have followed along good job! Your site is now ready for the future. To learn more about PHP, check out our developers guide to PHP coding standards.

Have you updated PHP for your WordPress site? Which version were you running before? Did you have any issues? Let us know in the comments section below!

The post How to Easily Check and Update the PHP Version of Your WordPress Site appeared first on Torque.

]]>
https://torquemag.io/2018/01/update-php-version-wordpress/feed/ 140
Preparing Your Site for PHP 7.2.0 https://torquemag.io/2017/10/preparing-site-php-7-2-0/ https://torquemag.io/2017/10/preparing-site-php-7-2-0/#comments Tue, 24 Oct 2017 19:26:33 +0000 https://torquemag.io/?p=82883 PHP has announced the availability of a third Release Candidate (RC3) for PHP 7.2.0. Currently, PHP 7.2.0 is in a development preview stage but is set to be released on November 30, 2017. With the prospect of a new PHP version on the horizon, you may be one of the many users who is wondering: Should I update? What benefits does this version offer? Is my site ready for the update? Before reading too much further, it’s important to note that 7.2.0 is a minor PHP release, which offers smaller tweaks and improvements. Larger releases include PHP 7.0, which is […]

The post Preparing Your Site for PHP 7.2.0 appeared first on Torque.

]]>
PHP has announced the availability of a third Release Candidate (RC3) for PHP 7.2.0. Currently, PHP 7.2.0 is in a development preview stage but is set to be released on November 30, 2017. With the prospect of a new PHP version on the horizon, you may be one of the many users who is wondering: Should I update? What benefits does this version offer? Is my site ready for the update?

Before reading too much further, it’s important to note that 7.2.0 is a minor PHP release, which offers smaller tweaks and improvements. Larger releases include PHP 7.0, which is quickly becoming widely adopted due to the speed gains it offers. Roughly 13 percent of WordPress users are using PHP 7 currently, while over 40 percent of users are still using version 5.6.

Keep in mind: WordPress has officially updated their System Requirements page to strongly recommend PHP 7 at a minimum.

In this article, we will review new features and deprecated functions so you can be prepared when PHP 7.2.0 is released to the public.

Core Changes

With PHP 7.2.0, there are a few more major changes to PHP core code to be aware of:

Type Annotation Changes

It is now possible to remove argument type annotations when overriding an inherited method – This allows developers to both drop a type from a subclass entirely, and also to add types to a method of a class without breaking the class. This change is useful for developers who need to add a new type when other classes extend that class. Before, these new types would potentially break the classes extending the original class as the method signature would then mismatch in instances where the new types were used.

The “object” type annotation is now supported – The primary change here is that PHP core now allows users to specify that an “object” type is expected when declaring what argument “type” to expect in return. The “object” name is now a reserved classname as a result. Below is an example of code from PHP where the “object” parameter type is expected:

function acceptsObject(object $obj) {
   ...
}

// This code can be statically analyzed to be correct
acceptsObject(json_decode('{}'));

// This code can be statically analyzed to be correct
acceptsObject(new \MyObject());

// This can be statically analysed to contain an error.
// and would throw an TypeError at runtime.
acceptsObject("Ceci n'est pas une object.");

Widened Support

It is now allowed to override an abstract method with another abstract method in a child class – This is a pretty minute change as there are very few uses for it, but essentially this change allows for the extension of one abstract method with another abstract method. PHP provides the following example:

<?php
abstract class A           { abstract function bar(stdClass $x);  }
abstract class B extends A { abstract function bar($x): stdClass; }
class C extends B          { function bar($x): stdClass{} }
// Fatal error: Can't inherit abstract function A::bar()
// (previously declared abstract in B)

Previously saying class C extends B was unsupported because A is already abstract, and C is extending an abstract class (B) which extends another abstract class (A). With PHP 7.2.0 this would be supported.

A trailing comma in group use statements is now allowed – This simply extends the support of trailing commas from arrays to now be supported in all list types. Since arrays have long had the ability to divide lists using commas, this change was to make lists of all types more intuitive. In the following example from PHP, a class member list would support using commas as a divider like so:

  const
       A = 1010,
       B = 1021,
       C = 1032,
       D = 1043,
   ;

Security Changes

PHP 7.2.0 also involves some neat security improvements, most of which center around new libraries for encryption and passwords.

The Sodium crypto-library has been added to PHP core. Sodium is a cryptographic library for encryption and decryption methods. Libsodium offers cross-platform compatibility and the ability for password hashing, generating random numbers and hashes, and many options for encrypting data both stored in Memory and not. See their FAQ for more information about coding with libsodium.

PHP has also been updated to support Argon2i hashes for passwords when compiled with libargon2. This introduction is a more secure alternative to Bcrypt hashing. The PASSWORD_ARGON2I constant has been introduced for use with password functions as a result of this change, and several cost factors can be set as constraints: Memory, Time, and Threads. By contrast, Bcrypt only accepted one cost factor.

Mcrypt (a file encryption tool using the libmcrypt library) is deprecated as an extension and has been moved to PECL. Users are strongly discouraged from using this extension as it has not been actively maintained since 2007. OpenSSL or libsodium are acceptable alternatives.

New Global Constants

New global constants have been added within PHP 7.2.0, many of which relate to new extensions or features.

Core

PHP_FLOAT_DIG – The number of decimal digits, that can be rounded into a float and back without precision loss

PHP_FLOAT_EPSILON – The smallest representable positive number x, so then x + 1.0 != 1.0

PHP_FLOAT_MIN – The minimum representable float number

PHP_FLOAT_MAX – The maximum representable float number

The above constants relate to the concept of floating point numbers, otherwise known as floats, doubles, or real numbers. These changes come because the pack() and unpack() functions now support float and double in both little and big endian in this release.

PHP_OS_FAMILY – The current operating system family

Filesystem

FILEINFO_EXTENSION – This constant defines a list of possible file extensions

GD

IMG_EFFECT_MULTIPLY – Overlays with a “multiply” effect.

IMG_BMP – Allows for .bmp (bitmap) file formats to be defined

PCRE

PREG_UNMATCHED_AS_NULL – Distinguish between unmatched subpatterns and empty matches by reporting NULL and “” (empty string), respectively.

Standard

PASSWORD_ARGON2_DEFAULT_MEMORY_COST – Defines the number of KiB that should be consumed or used in the hashing process

PASSWORD_ARGON2_DEFAULT_TIME_COST – Defines the number of iterations the hashing algorithm should take

PASSWORD_ARGON2_DEFAULT_THREADS – Defines the number of parallel threads the hashing algorithm should use in the hashing process

PASSWORD_ARGON2I – password_hash() can be set to the PASSWORD_ARGON2I algorithm to generate Argon2i hashes.

The new constants above relate to the addition of the Argon2i hashes in this PHP release. They are used as “cost factors” which allow constraints around usage. See the Security Changes section above for more information.

Deprecated Functions

With PHP 7.2.0 there are a few functions to be fully deprecated as well. If you want to use PHP 7.2.0 on your sites, you should search through PHP code in your plugins and theme to ensure none of these deprecated functions are called:

Core

__autoload – as of PHP 5.1, this function has been replaced by spl_autoload_register. The newer spl_autoload_register function allows for multiple autoloaded functions and will loop through these functions in whatever order they are defined in the code.

$php_errormsg – The php_errormsg function is intended to be used whenever a non-fatal error is produced, and when track_errors is enabled. This function has been deprecated in favor of error_get_last and error_clear_last instead, which offers a cleaner way of printing these errors and cover all use cases.

create_function() – In most cases, create_function() is used as a wrapper for eval() functions which are known to be security concerns. Additionally, create_function() tends to have poor performance implications. The use of closures is highly preferable, which were introduced in PHP 5.3.

(unset) cast – The (unset) cast will change a value to null. In truth (unset) expr just always returns null. However, the existence of this cast is confusing for developers as it doesn’t function the same as unset().

each() – The foreach() construct is highly preferable to the use of each() in coding, as the newer foreach() construct is about ten times faster. A deprecation notice will appear on the first iteration of each() only, since it is used most often in loops.

$errcontext argument of error handler – The last argument of set_error_handler() was “$errcontext” which provided the variables present when the error happened. Using an object debugger is preferable. Currently this argument does not trigger a deprecation warning.

EXIF

read_exif_data() alias – Has been deprecated. Use the exif_read_data() function instead.

GD

png2wbmp() and jpeg2wbmp() – Both functions have been deprecated, as WBMP file formats are no longer commonly used. Most mobile devices are fully capable of handling full-color images and videos.

GMP

gmp_random() – The gmp_random_bits function generates a random number between 0 and (2 ** bits) – 1 and the gmp_random_range function generates a random number between the set min and max. Together, these two functions replace the gmp_random() function which had to guess at the proper limb size and had platform incompatibilities.

Intl

INTL_IDNA_VARIANT_2003 – Deprecated in favor of INTL_IDNA_VARIANT_UTS46. Used for the variant parameter in the idn_to_utf8() function, which converts domain names from IDNA ASCII to Unicode.

Mbstring

mbstring.func_overload – This function was originally introduced to replace strings generated by functions with analog values instead. For instance, returning values in code points rather than bytes. This function is highly incompatible with almost all other code and the original creator has agreed it should be deprecated.

Standard

parse_str() without second argument – The default behavior of parse_str() is to translate a query string into an array when a second argument is present. The deprecated functionality is the action that previously happened when a second argument was not present: to parse the first (only) argument into the local symbols article. This was left over from very old register_globals functionality and has been deprecated.

assert() with string argument – Because the default functionality of assert() with a string argument is to run the string through eval(), using assert() with a string argument has now been deprecated. There is now an option to enable the zend.assertions ini option instead of evaluating the assertion expression.

What is your favorite feature of the new update? Let us know in the comments below. 

The post Preparing Your Site for PHP 7.2.0 appeared first on Torque.

]]>
https://torquemag.io/2017/10/preparing-site-php-7-2-0/feed/ 2
How to Remind Users to Upgrade to PHP 7 Using the WHIP Codebase https://torquemag.io/2017/06/remind-users-to-upgrade-to-php-7-whip/ Mon, 12 Jun 2017 16:31:03 +0000 https://torquemag.io/?p=81688 PHP 7  has been around for well over a year now, and yet only 4.5% of sites have made the upgrade from PHP 5. With users and their hosts lagging behind, a large number of sites remain more vulnerable to hacking and performance issues than their updated counterparts. As a WordPress developer, you hold much more sway and influence than you might think. Brands such as Yoast are asking you to use that power to help upgrade the internet as a whole. You can do this by adding nudges to your plugins using Yoast’s WHIP framework. This helps you inform the user […]

The post How to Remind Users to Upgrade to PHP 7 Using the WHIP Codebase appeared first on Torque.

]]>
PHP 7  has been around for well over a year now, and yet only 4.5% of sites have made the upgrade from PHP 5. With users and their hosts lagging behind, a large number of sites remain more vulnerable to hacking and performance issues than their updated counterparts.

As a WordPress developer, you hold much more sway and influence than you might think. Brands such as Yoast are asking you to use that power to help upgrade the internet as a whole. You can do this by adding nudges to your plugins using Yoast’s WHIP framework. This helps you inform the user about why they should always run the latest PHP version. It also makes your plugin run more smoothly in production, so it’s a win-win proposition.

In this article, we’ll explain why it’s worth getting as many people as possible to upgrade to PHP 7. Then, we’ll show you how to add a PHP version nudge to your own WordPress plugin in three steps. Let’s get started!

Why It’s Worth Compelling Users to Upgrade to PHP 7

WordPress.org always advocates that users build their sites using the latest version of PHP. This is for many reasons, including security, implementing modern coding standards, and generally providing an improved performance.

PHP 7 landing page
PHP 7 has a number of benefits over its previous versions – most notably, speed.

Unfortunately, of websites using PHP, a whopping 94.5% are still running the previous version – and a quarter are running on the most recent PHP 5.6. Developers will often let new major versions mature before switching. PHP 7 has now been available for a year and has proven itself in production, yet only 4.6% of PHP users have upgraded.

More recently, Yoast – developers of the Yoast SEO plugin – has begun pushing users to upgrade from within the plugin over the last few releases. Though initially fearful such a nudge might annoy their users, de Valk says that “Negative feedback has been absolutely minimal.” Yoast’s consensus is that developers should be compelling users to upgrade. On the whole, when newer and better versions of software exist, there is very little reason not to update them.

Because of this, Yoast has released a public package called WHIP, which helps you implement your own PHP upgrade nudge within a WordPress plugin. It’s found on GitHub, and is easy to implement. With that in mind, let’s take a look at how to do so.

How to Implement the WHIP Codebase Into Your Own Plugin (in 3 Steps)

Of course, this will be most useful to those who build and distribute WordPress plugins. Over the next three steps, we’ll show you how easy it is to add PHP upgrade notices to your plugins with Yoast’s WHIP.

1. Install Local Development Prerequisites for the WHIP Codebase

To install the WHIP codebase in your plugin, you’ll first need to install Composer – a dependency manager for PHP, which enables you to install WHIP rapidly:

Composer dependency manager

To get started, download Composer to your computer. You can enter the following commands in to your console to do this.

php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
php -r "if (hash_file('SHA384', 'composer-setup.php') === '669656bab3166a7aff8a7506b8cb2d1c292f042046c5a994c43155c0be6190fa0355160742ab2e1c88d40d5be660b410') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;"
php composer-setup.php
php -r "unlink('composer-setup.php');"

Next, follow the appropriate installation steps for your operating system – Windows or Linux, Unix, and OS X/macOS. At this point, you should already have a plugin to distribute that you plan on adding a nudge to. If so, make sure you’ve set up a local development environment (loaded with WordPress and your plugin) for you to work in.

2. Install the WHIP Core Codebase to Your Plugin

Once Composer is installed, and your local development environment is ready, navigate to your target plugin folder within the console. Your plugin is likely under a path similar to /wp-content/plugins/example, where example is the name of your plugin.

Installing Yoast WHIP using composer
An example of installing Yoast WHIP using Composer.

After locating your plugin folder, simply type the installation command for WHIP into the console:

composer require yoast/whip

This will add a new folder called vendor to your plugin. However, that’s not all you need to do. New Composer users still need to notify your plugin that these new files exist, and you’ll need to ‘require’ the Composer autoloader.php file somewhere in your plugin’s code. Here’s an example of code that works within the main plugin file:

if ( file_exists( plugin_dir_path(__FILE__) . '/vendor/autoload.php' ) ) {
    require plugin_dir_path(__FILE__) . '/vendor/autoload.php';
}

At this point, the WHIP codebase should be included with the rest of your plugin. The final step is to actually trigger the front end nudge.

3. Trigger the Front End Notice for Old PHP Versions

For the final step, you’ll need to trigger the notification for users running an old PHP version. Once you’ve included the Composer autoload.php file, you’ll want to add the function that checks for the PHP version, then return a notification if it is below a certain number.

You can choose your minimum required level of PHP depending on what you think is appropriate. In this example, you can see it triggers only if the PHP version is lower than 5.6:

whip_wp_check_versions( array(
    'php' => '>=5.6',
) );

The WHIP function for this is highly configurable. For example, there are options for customizing:

  • Which version of PHP you want to check for, depending on how strict you want your plugin to be.
  • Host-specific messages, if you are a web host distributing WordPress plugins.
  • Recommendation links, if you don’t want to use Yoast’s provided landing pages.

Once you’ve saved your changes, check your WordPress dashboard in your browser for the new message.

Yoast WHIP Notification in action
An example of the Yoast WHIP PHP upgrade notification.

Upgrading your PHP version has wide-reaching ramifications for users, so we believe a dashboard message is well worth implementing – and Yoast’s WHIP codebase makes it a snap!

Conclusion

Compelling users to upgrade to PHP 7 helps improve the performance of your plugins, thanks to the many benefits the latest version has over its predecessors. While the version notice may seem unneeded at first, your users will probably be thankful once they’ve made the switch.

To install Yoast’s WHIP codebase in your plugins to help encourage users to switch, you need to:

  1. Install local development prerequisites for the WHIP codebase.
  2. Install the WHIP core codebase to your plugin.
  3. Trigger the front end notice for old PHP versions.

Do you have any questions about adding a PHP version upgrade notice to your WordPress plugin? Let us know in the comments section below!

Image credits: Andrew Measham.

The post How to Remind Users to Upgrade to PHP 7 Using the WHIP Codebase appeared first on Torque.

]]>
3 Compelling Reasons You Should Make the Switch to PHP 7 for WordPress https://torquemag.io/2017/05/compelling-reasons-you-should-switch-to-php-7/ https://torquemag.io/2017/05/compelling-reasons-you-should-switch-to-php-7/#comments Mon, 08 May 2017 15:30:22 +0000 https://torquemag.io/?p=81590 Though it’s the most widely used web programming language, PHP has taken a lot of flack in development circles. However, after a long period with no major updates, PHP 7 has finally been released with many great new features – and it will also help you keep your WordPress website in tip-top shape. Simply put, PHP is at the heart of the WordPress core, and to get the best possible performance for your site, you should always use the latest version. However, while some hosts are being proactive, you may need to give your particular host a nudge if they’re dragging their […]

The post 3 Compelling Reasons You Should Make the Switch to PHP 7 for WordPress appeared first on Torque.

]]>
Though it’s the most widely used web programming language, PHP has taken a lot of flack in development circles. However, after a long period with no major updates, PHP 7 has finally been released with many great new features – and it will also help you keep your WordPress website in tip-top shape.

Simply put, PHP is at the heart of the WordPress core, and to get the best possible performance for your site, you should always use the latest version. However, while some hosts are being proactive, you may need to give your particular host a nudge if they’re dragging their feet with regard to updating PHP on your server.

In this article, we will first introduce you to PHP and it’s most recent update, then offer three compelling reasons for why it’s worth upgrading. Finally, we’ll show you how to get up to date. Let’s get started!

An Introduction to PHP and the PHP 7 Update

As you may be aware, PHP is best known as a server-side scripting language for the web, although it began as the personal creation of Rasmus Lerdorf in 1994. Due to its ease-of-use, it grew into a language with a low barrier of entry, enabling both experienced and green programmers to use it. As a result, it’s now used for over 80% of the web – including WordPress:

Server Side Script Languages

Even so, PHP went for twelve years without receiving a major version update. That’s a long time in the ‘real world’, but in internet time it’s practically prehistoric. After a few version updates to PHP 5 (along with a failed attempt at building PHP 6), PHP 7 became the new release candidate in 2014.

Although we’re just beginning to discuss its merits now, PHP 7 has actually been available since 2015. It means leaving PHP 5 behind for the good of the development community and the performance of your website should be your current goal.

3 Compelling Reasons You Should Make the Switch to PHP 7 for WordPress

Now you’re up to speed with why PHP 7 is so significant, it’s time to discuss three major reasons you should upgrade. By the time we’re finished, you should have a clear understanding as to how PHP 7 will benefit your WordPress website.

Reason 1: WordPress Advocates for PHP 7

In a nutshell, we believe that keeping your software up to date is a good idea for a myriad of reasons – we’ve previously talked about those in-depth while showing you how to upgrade WordPress. WordPress stands behind this, too. Updates are (of course) necessary for security reasons, to fix bugs, and to add new features and functionality, so it makes sense to apply these same standards to your WordPress server too.

Official WordPress.org server requirements
The official WordPress site recommends PHP 7.

Leading up to PHP 7’s official release in 2015, the WordPress core developers slaved away to practically guarantee compatibility in advance. What’s more, Aaron Jorbin published a statement at Make WordPress stating:

WordPress continues to encourage all users to run the latest and greatest versions of PHP, including PHP 7 upon its release.

It means WordPress’ core has been ready for PHP 7 since its release in December 2015.

However, although core has been ready for a while, the same might not be said of any plugins and themes. Because they’re essentially third-party additions to core, there’s less control over their compatibility. It means that you should ensure any third-party code, plugins, and themes you use are also PHP 7 compatible before upgrading to avoid nasty surprises. To help, you could use WP Engine’s PHP 7 Compatibility Checker plugin, which does what it says on the tin:

The PHP Compatibility plugin

Once you run the test with the plugin, there are three options for handling errors on the compatibility report:

  1. Resolve them by fixing the code yourself (which could mean adopting the plugin).
  2. Reach out to the developers to make sure it gets fixed.
  3. Replace them with plugins that are already PHP 7 compatible (which is as simple as running them through the plugin again).

Once you’ve cut any non-PHP 7 compliant plugins and themes, you should be ready to upgrade!

Reason 2: PHP 7 Offers Better Development Features

PHP has always been known for its ease of entry, which is one reason why it’s a popular language for many new web developers. Unfortunately, this can lead to poorly written code full of security holes and performance issues.

To help combat this, many aspects of PHP 7 attempt to steer new developers in the right direction. It does this by removing poorly written, outdated functions previously kept in for backwards compatibility reasons. With the adoption of PHP 7, we should begin to see a higher standard of PHP coding. In turn, this should also help PHP become more respected as a development language, attracting talent that has otherwise avoided it.

Spaceship operator in PHP 7
The spaceship operator is a new function available in PHP 7.

Here are a few of the new features introduced in PHP 7, and why they’re so interesting:

Of course, this is an incomplete list of features. However, these are just some of the more exciting inclusions in PHP 7.

Reason 3: PHP 7 Is Blazingly Fast and More Secure

Another reason PHP 7 removed so many old, deprecated functions was to make room for the new features we previously discussed. This cleared up a lot of space, which enabled PHP 7 to grow without bloating in size. As such, PHP 7 is a much leaner and more efficient language. What’s more, it also ships with the new Zend engine, which offers much faster processing.

To order to ascertain exactly how fast PHP 7 is compared to its previous versions, we ran some speed benchmarks. As you can see, PHP 7 blows other versions out of the water:

PHP7 speed test

At a base level, speed will help your WordPress site in two major ways: usability and Search Engine Optimization (SEO).

Site speed directly impacts responsiveness, which makes it feel fun to use. What’s more, good usability keeps visitors on your site longer, and can potentially improve your conversion rates. Site speed is also a ranking factor for search engines, and a high ranking website stands to earn greater traffic.

As for security, we’ve already discussed how PHP 7 makes it harder to write poor code by default. Additionally, there are also a few new tools for serialization and cryptographically secure random numbers. It means that even if you never write a line of PHP code, the developers who do can put out better work thanks to PHP 7. Of course, to benefit accordingly, it needs to be running on your server.

Finally, previous versions of PHP have been around for so long that there are many well-documented hacks for each. (You can learn more about server security at the WordPress Codex.) As PHP 7 is newer, there are likely fewer known ways to exploit a PHP 7 specific weakness. This also ties in with our advice about keeping WordPress up to date, as each release often comes with security fixes.

How to Upgrade to PHP 7

If you administrate your own server, you can upgrade to PHP 7 yourself (although you’ll want to carry out a common sense check first). Otherwise, we recommend reaching out to your hosting provider to ask for a PHP upgrade. Here’s a sample email you can send them, adapted from a WooCommerce template:

Dear host,

I run WordPress on one of your servers, and WordPress.org lists PHP 7 as the recommended version of PHP on their requirements page (https://wordpress.org/about/requirements/).

Can you please let me know if my account supports PHP 7, and how can I upgrade?

If they won’t comply, it’s probably time to find a host that supports PHP 7. We’ve also written extensively on PHP 7-related topics over the past couple of years, and given its adoption, we plan on continuing to do so in the future!

Conclusion

PHP 7 comes with a lot of improvements over its predecessors that will directly benefit your WordPress website. Regardless, it’s sharply becoming a non-conditional requirement for running a secure and speedy WordPress website, so it’s important to make the switch sooner rather than later.

In this piece, we’ve offered three compelling reasons to upgrade to PHP 7. Let’s quickly recap them:

  1. WordPress.org encourages users to always use the latest version of PHP for improved security and performance.
  2. PHP 7 enforces better coding standards, improving coding standards across the board.
  3. The latest PHP version can run significantly faster than its predecessors, which will improve your site’s speed as well.

What questions do you have about making the switch to PHP 7? Let us know in the comments section below!

Image credits: Courtney Recker.

The post 3 Compelling Reasons You Should Make the Switch to PHP 7 for WordPress appeared first on Torque.

]]>
https://torquemag.io/2017/05/compelling-reasons-you-should-switch-to-php-7/feed/ 1
What 2017 Will Mean for Your WordPress Workflow https://torquemag.io/2017/01/2017-wordpress-workflow/ Mon, 09 Jan 2017 16:50:41 +0000 https://torquemag.io/?p=80789 2016 was a big year for WordPress, and 2017 is already set to be even bigger. With Let’s Encrypt changing the SSL landscape, Automattic changing the criteria of their recommended hosting solutions, and the REST API continuing its emergence, there’s a lot to consider in the months to come. So what does all of this mean for WordPress developers and users? In a nutshell, it means a lot! The new year will bring with it huge changes to the world of WordPress, which could take you by surprise if you’re not up to speed. In this post, we’ll dust off […]

The post What 2017 Will Mean for Your WordPress Workflow appeared first on Torque.

]]>
2016 was a big year for WordPress, and 2017 is already set to be even bigger. With Let’s Encrypt changing the SSL landscape, Automattic changing the criteria of their recommended hosting solutions, and the REST API continuing its emergence, there’s a lot to consider in the months to come.

So what does all of this mean for WordPress developers and users? In a nutshell, it means a lot! The new year will bring with it huge changes to the world of WordPress, which could take you by surprise if you’re not up to speed.

In this post, we’ll dust off the crystal ball and walk you through three predictions for WordPress 2017. We’ll also take a look at how it could affect your workflow going forward. Let’s get cracking!

Potentially Switching Hosting Providers

A couple of years ago, Google announced HTTPS as a ranking factor. It’s led to the emergence of services such as Let’s Encrypt, which makes it easier for website owners to acquire SSL certificates. Fast forward to December 2016, Matt Mullenweg stated:

Early in 2017, we will only promote hosting partners that provide an SSL certificate by default in their accounts.

For the uninitiated, having an SSL certificate installed on your site means the link between your site’s server and your browser will be encrypted. This year, we can expect WordPress to debut features such as API authentication, which would require hosts to have HTTPS available.

As a result, WordPress will no longer be promoting hosting providers that don’t provide an SSL certificate by default. Simply put, if your current host doesn’t provide the option to encrypt your connection, it may be time for you to make the switch to one who does.

To decide, firstly check WordPress.org. The hosting recommendations here were updated last year, so if your WordPress site is hosted on any of these platforms, you’re good to go.

Integrating PHP 7

Around mid-2017 we can expect WordPress to update the recommended PHP version for servers from 5.6 to 7, which means some big incoming changes. Some hosting providers have already started adopting the latest release, and are prepared to fully support it for their users.

A web page featuring some of the features of PHP 7.
Just some of the benefits of adopting PHP 7.

There are two main advancements that PHP 7 brings:

  1. A brand new engine. PHP 7 has let go of the old Zend Engine II, replacing it with the brand new PHPNG engine. Benchmark tests have reported that most applications run twice as fast on the new engine.
  2. Improved language features. It comes with a myriad of powerful language features that make development more streamlined, such as the new ‘spaceship’ operator and scalar type hints.

Although PHP 7 is new technology, we’ve previously discussed how some aren’t too keen on its adoption. As is the case with any new technology, PHP 7 has its own drawbacks, such as deprecated itemsmultiple default clauses, and engine exceptions. That being said, the benefits far outweigh the negatives, and in all honesty, there’s little to stop PHP 7’s imminent arrival in any case.

Here’s a quick outline of what you need to do to make a successful switch when the time comes:

  1. Firstly, take a look at any backwards incompatibility issues relating to WordPress’ core, themes, and plugins.
  2. Upgrade to PHP 7 on your test server.
  3. Test your site on your localhost setup before pushing it live.
  4. Perform benchmarks to see where you stand, tweaking your settings accordingly.

For a more in-depth look, our Developer’s Checklist for PHP 7 is a great starting point for those of you who want to make the switch without missing a step.

Implementing the WordPress REST API

The WordPress REST API logo.
The WordPress REST API has already started seeping into the platform’s infrastructure.

The shape of the WordPress REST API is now becoming more apparent. In his recent State of the Word address, Matt Mullenweg has delved a little deeper into how the REST API pertains to WordPress; and although WordPress 4.7 included content end points for the API, the WordPress admin will be the first to potentially benefit.

Although we’re still scratching the surface of the REST APIs capabilities, it seems we’re definitely headed in the right direction. Of course, we’ll likely find out more in March at the next A Day of REST conference.

It’s no secret that the REST API is going to be at the very center of WordPress’ future. Theme and plugin developers have already started researching how to leverage the REST API into future projects. What’s more, many WordPress website owners have accepted that the future state of their sites will largely depend on the possibilities of the new technology. To that end, there are some notable real world REST API projects already underway, including include CalypsoEvent Espresso, and Human Made.

What this means for developers is pretty clear: it’s time to embrace JavaScript. We’ve covered the topic previously, and quite simply, cracking out the books and getting to know this language (if you don’t already) is going to be pretty important to your WordPress future in 2017.

Conclusion

WordPress is on the cusp of some major changes that are likely to affect both developers and end users. Understanding the anticipated changes, and adapting to them early on, can help you get things in order before it’s too late.

In this post, we’ve offered three aspects of how WordPress’ development in 2017 will affect your workflow. Let’s recap:

  1. Given that WordPress will only recommend hosts offering SSL certification by default, you may need to make the switch to a WordPress recommended host.
  2. PHP 7 is soon going to be the norm. If you haven’t updated to the latest version already, we suggest doing so now.
  3. The time has come to begin researching the REST API and JavaScript, and using it in your future projects.

What are your predictions for WordPress in 2017? Let us know in the comments section below!

Image credit: geralt.

The post What 2017 Will Mean for Your WordPress Workflow appeared first on Torque.

]]>
Developer’s Checklist for PHP 7: 6 Things to Bear in Mind https://torquemag.io/2017/01/developers-checklist-php-7/ https://torquemag.io/2017/01/developers-checklist-php-7/#comments Mon, 02 Jan 2017 17:30:33 +0000 https://torquemag.io/?p=80759 Powering over 76 million websites and holding a 59% CMS market share, WordPress continues to dominate the web in 2017. However, with the new year comes new challenges. Since PHP 7 could be the minimum requirement for running self-hosted WordPress in 2017, updating your server’s version of PHP to PHP 7 could be a necessary step. In this post, we’ll cover why you should upgrade to the latest version, how to upgrade your server to PHP 7, any new features, inconsistency fixes, its overall performance, any backwards incompatible changes, the compatibility checker, and a note on PHP 7 benchmarks. Let’s […]

The post Developer’s Checklist for PHP 7: 6 Things to Bear in Mind appeared first on Torque.

]]>
Powering over 76 million websites and holding a 59% CMS market share, WordPress continues to dominate the web in 2017. However, with the new year comes new challenges. Since PHP 7 could be the minimum requirement for running self-hosted WordPress in 2017, updating your server’s version of PHP to PHP 7 could be a necessary step.

In this post, we’ll cover why you should upgrade to the latest version, how to upgrade your server to PHP 7, any new features, inconsistency fixes, its overall performance, any backwards incompatible changes, the compatibility checker, and a note on PHP 7 benchmarks.

Let’s get started!

1. Upgrading WordPress to PHP 7

The arrival of PHP 7 brings big changes into view, including the latest PHPNG (Next Generation) engine and a host of powerful new features. It’s a good idea to upgrade your version of PHP if you want to keep your WordPress website running smoothly.

If you’re running a WordPress website then you already have PHP installed. Why should you upgrade its version when everything is seemingly running so smoothly?

  • Minimum requirements. The minimum requirements for running WordPress are going to be bumped up soon; even as early as mid–2017.
  • Security and stability. New updates often have patches for security flaws, and PHP is no exception to this.
  • Plugin and theme compatibility. Plugin developers are going to update to the latest version, as well. Sooner or later the plugins you have installed won’t be compatible with the version of PHP you’re using. The same goes for WordPress themes and external scripts.

Of course, it does take time for developers to adopt new technologies. It’s likely that not all of your plugins, themes, and scripts will be compatible with the latest version once you upgrade. To review the changes beforehand, you can install the PHP Compatibility Checker.

PHP Compatibility Checker

You can upgrade WordPress to PHP 7 yourself via SSH, depending upon your server type. Alternatively, you can also get the job done by logging into your hosting provider’s cPanel and navigating to PHP Version Manager to choose the latest PHP version. That should be all there is to it!

2. New Features

PHP 7 features

We already know that PHP 7 is soon going to be a requirement for running WordPress. But why is that so? According to Matt Mullenweg, upcoming versions of WordPress are set to include functionality that relies on the latest version of PHP. Here are some new features we can expect to see.

PHP 7 comes with two new operators – the spaceship operator and the null coalesce operator. The spaceship operator is more commonly known as the combined comparison operator, and is essentially a combination of three individual operators. It works by checking the values with each operator individually. The spaceship operator is hugely beneficial for developers who find themselves having to create sorting algorithms. In addition, its basic working principle makes for blazing fast results.

Null coalesce (also called the if-set-or operator) is a simple way to assign a variable to the default value if it doesn’t already contain a value. It works by checking if the operand on the left holds some value. If it doesn’t, it returns the right operand. The best part about the null coalesce operator is that it’s stackable.

PHP 7 also comes with scalar type hints – int, float, string, and bool. These fundamental types make it easier to read code, and give the developer more control over variables. By default these type declarations are non-strict. However, using them is far easier if you enable strict requirements.

Lastly, the new technology also supports return type hints, which are specified with a colon followed by the return type. With this addition, you can be sure what a function will return, which makes it easier to test them out. From a developer’s point of view, these new type declarations force things to be how they are supposed to be.

3. Upcoming Inconsistency Fixes

PHP 7 will bring some much needed inconsistency fixes to the table. Perhaps the most beneficial development in this space is the addition of Abstract Syntax Trees (AST). These trees are used as intermediary representations of code during the compilation process. Abstract syntax trees can be used to write opcodes that are more performant. In addition, developers can clear up edge case inconsistencies. The key benefit here is that you don’t have to worry about being bogged down in concrete syntax issues.

In addition to the inclusion of abstract syntax trees, PHP 7 also comes with uniform variable syntax. The addition of this concept significantly reduces the number of inconsistencies that arise when expressions are evaluated. It ensures that references and expressions are accessed from left to right instead of right to left. With this, expressions which may have been invalid before would now be valid.

4. Boosting Overall Performance

One of the biggest reasons behind upgrading to the latest version of PHP is the massive performance improvements that it brings to the table. The significant improvement in performance is mainly attributed to the PHPNG engine. The latest PHPNG engine makes it just as fast (some argue even faster) than HHVM. According to the official benchmark results, most applications running on PHP 5.6 ran twice as fast on PHP 7. Here are some more statistics:

Since the latest PHP version handles more than twice as many requests each second, developers can expect to see a 100 percent improvement in terms of performance on WordPress websites. In simple English, this means that your code will execute faster, and you’ll need a fewer number of servers to cater for the same number of users. These huge performance gains, in addition to optimized memory usage, gives developers strong reasons to make the switch.

5. Backwards Incompatible Changes

Still not sure whether you should upgrade to PHP 7? Let’s take a look at some things that could (potentially) break your site if you continue running it on an older version of PHP.

To establish some context to backwards compatibility, consider the following:

Code written a decade ago should run smoothly today and a decade from now.

As a developer, you can’t expect any language to conform to this, let alone PHP. Each new release brings with it some backwards compatibility and even more important, some backwards incompatibility, including:

  • Deprecated items. A handful of deprecated items have been removed from PHP 7. Now’s a good time to go through the list and make sure you’re not using any of them. If you find a match, you can replace it easily with new tags and functions.
  • Multiple default clauses. Multiple default clauses in switch statements do not cause warnings, which also make it difficult for developers to detect their mistake. PHP 7 introduces a detailed warning – Fatal Error: Switch statements may only contain one default clause.
  • Engine exceptions. The current version of PHP displays fatal and recoverable fatal errors. PHP 7 replaces them with exceptions. Exceptions make it simpler for developers to identify the errors, log them, and take actionable steps to resolve them.

6. A Note on PHP 7 Benchmarks

By now you’ve probably heard that PHP 7 is fast over a dozen times. But how fast is it really?

PHP 7 running on the latest PHPNG engine is notably better than HHVM – in terms of both overall speed and memory optimization. From a purely WordPress perspective, benchmarks show that PHP 7 delivers impressive responsive times. A site that previously loaded in 1.2s on PHP 5.5 loaded in 4ms on PHP 7.

PHP 7 performance

The performance benchmarks published by Zend’s Performance Team show that PHP 7 will not only execute your code faster but will also require fewer servers to serve the same number of users. WP Engine’s publication, PHP 7: The Way of the Future, provides an in-depth performance analysis of the new technology on WordPress. For even more information, Medium’s PHP MVC Framework Showdown: 7.0 Performance is incredibly detailed.

Conclusion

With PHP 7 being the minimum requirement for running a self-hosted WordPress site in 2017, it’s high time to get things in order and understand the upcoming technology. Let’s recap our checklist of things to know:

  1. There are good reasons to upgrade to PHP 7, and you can make the switch yourself through SSH or through your cPanel account.
  2. PHP 7 brings with it new operators and type hints that are set to ease development and make your code more readable.
  3. Abstract syntax trees and uniform variable syntax reduce the inconsistencies we saw in previous versions of PHP.
  4. PHP 7’s PHPNG engine may just be the biggest reason behind upgrading your servers.
  5. Be sure to run through our list of backwards incompatible changes before upgrading to PHP 7 to avoid any unprecedented pitfalls.
  6. The latest technology has some massive power running under the hood, which is arguably notably faster than HHVM.

Do you have any questions about how to get up and running with PHP 7? Let us know in the comments section below!

Image credit: OpenClipart-Vectors.

The post Developer’s Checklist for PHP 7: 6 Things to Bear in Mind appeared first on Torque.

]]>
https://torquemag.io/2017/01/developers-checklist-php-7/feed/ 1
An Introduction To Return Type Declarations In PHP7 https://torquemag.io/2016/09/introduction-return-type-declarations-php7/ https://torquemag.io/2016/09/introduction-return-type-declarations-php7/#comments Wed, 14 Sep 2016 18:39:52 +0000 https://torquemag.io/?p=80091 Last week, I wrote about type hinting, in PHP. Type hinting makes the intent of a function clearer and forces the values to show a specific type of value. While having a function that only accepts a certain type of value removes the need to check a variable’s type from the function, it doesn’t mean you don’t have to check that type first before calling the function. Passing a variable of the wrong type creates a fatal error. For example, get_post_meta() can return pretty much any type of data. If you’re using it in a way that you expect it to […]

The post An Introduction To Return Type Declarations In PHP7 appeared first on Torque.

]]>
Last week, I wrote about type hinting, in PHP. Type hinting makes the intent of a function clearer and forces the values to show a specific type of value.

While having a function that only accepts a certain type of value removes the need to check a variable’s type from the function, it doesn’t mean you don’t have to check that type first before calling the function. Passing a variable of the wrong type creates a fatal error.

For example, get_post_meta() can return pretty much any type of data. If you’re using it in a way that you expect it to return an array, you still must check that it returned the expected result. Therefore if you had a function that required an array for one of its parameters, you would need to check that you got a result of the expected type from get_post_meta(), not false or some other type.

If you could build an abstraction around get_post_meta() that was guaranteed to provide an array always, then you could safely pass its return value to a function that requires an array.

In PHP5 we can write functions that should always return an array, but we have no way to declare it programmatically as such. Yes, inline documentation helps humans and IDEs know what to expect. But that doesn’t help the compiler or guarantee results.

PHP7 introduces return type declarations, which allow us to do just that. A return type declaration makes it so a function’s return value must be of a specific type.

Pros And Cons Of Return Type Declarations

There are two major arguments for using return type declarations. The first is performance, which is directly affected because the return type is explicitly declared. This means that the PHP compiler does not have to figure it out, which in turn makes compiling faster.

The other argument for using return type declarations is similar to that for using type hinting: it makes the intent and expected usage of code for clear. Just like type hinting, you lose some of the flexibility that using a dynamically typed language provides. So, you must decide if it is worth trading that flexibility for clarity and possible performance gains.

Also, since return type hinting is not backwards compatible with PHP5, it’s not yet a good idea to use it in a WordPress plugin or theme that will be released publicly. Even if you were to build in version checks, WordPress.org does not allow plugins or themes to use syntax added in PHP 5.5 or later.

On the other hand, if you are working on a bespoke site that runs PHP7 and a PHP7 feature such as this is useful to you, why wouldn’t you use it?

An Example

In the introduction to this post I discussed the problems with relying on assuming that a function like get_post_meta() will always return an expected value. Even if you always put an array in a specific meta key, what happens if no data has been set for a specific post or if you try and get post meta for a non-existent post?

If your goal is to use a post meta value with a function that requires an array, in PHP5 you are forced to test the value returned by get_post_meta() every time. In PHP7 you could write an abstraction around get_post_meta() that not only ensured you were always getting back an array, but made it explicit through return type declarations.

Here is an example class that does just that:

<?php
class get_post_meta {
	protected $post;
	
	public function __construct( WP_Post $post ) {
		$this->post = $post;
	}
	public function get_all() : array  {
		return get_post_meta( $this->post->ID );
	}
	public function get_key( $meta_key ){
		$meta = get_post_meta( $this->post->ID, $meta_key );
		if( ! is_array( $meta  ) && ! empty( $meta ) ){
			return [ $meta ];
		}elseif ( empty( $meta ) ){
			return [];
		}else{
			return $meta;
		}
		
	}
	
}

 

As you can see, we have two methods here that will always return an array. This is obvious to us as humans reading the code — if we know the new syntax. It is also will make for less code — no additional type checking code required — and will be faster for the PHP compiler to parse.

A New Syntax

Type hinting uses a new syntax that is not backwards compatible with PHP5. Here is a basic example of this syntax:

<?php
function total_posts( WP_Query $query ) : int {
	return count( $query->posts );
}

In PHP5, this would generate a fatal error with this message:

Parse error: syntax error, unexpected ‘:’, expecting ‘{‘

In PHP7 this is interpreted as a return type declaration. Because the declaration is “int” this function has to return an integer or it will cause an error.

Here is an example, that uses type hinting and return type declarations to make a simple WordPress REST API client:

<?php
class posts {
	protected $root;
	protected $posts;
	public function __construct( string $wp_root ) {
		$this->root = $wp_root;
	}
	public function query( int $page ){
		$headers = array('Accept' => 'application/json');
		$request = Requests::get( $this->root . 'posts/', $headers, [ 'page' => $page ]) ;
		$this->posts = json_decode(  $request->body );
	}
	public function get_total_posts() : int {
		if( empty( $this->posts ) || ! is_array( $this->posts ) ){
			return 0;
		}
		
		return count( $this->posts );
	}
	
	public function get_posts() : array {
		return $this->posts;
	}
}

The last two methods in this class use return type declarations. The get_total_count() method uses an int type declaration and therefore must return an integer, while the get_posts() method uses an array return type declaration and therefore must return an array.

Keep in mind this example uses the Requests library, which is included in WordPress 4.6 or later.

Should You Use Return Type Declarations?

PHP became so popular because of how flexible and relatively easy it is to learn. A lot of that is due to the flexibility provided by dynamic typing. But this flexibility has limited PHP’s performance. PHP powers some of the most trafficked sites on the internet — WordPress.com, Facebook, Wikipedia, Etsy, and more. New language conventions that make PHP less flexible, but more performant are necessary to meet the challenges of using PHP at that scale.

Personally, I’m not making top 10 websites, but these new language constructs still matter to me. WordPress is awesome because of what it can do on a small server. The more performant our code is, the less server resources we need and that’s a big deal in the WordPress world, where code is expected to run on shared hosting and enterprise environments.

Our language is maturing and what we can do with it is very exciting. I hope that this article will inspire you to spin up a PHP7 powered WordPress site on your computer and start learning these exciting new features. They are not hard, but if you’re looking to improve your site’s performance and to be prepared for WordPress’ hopefully, eventual shift to embracing non-backwards compatible features of PHP7 learning PHP7 return type declarations is essential.

The post An Introduction To Return Type Declarations In PHP7 appeared first on Torque.

]]>
https://torquemag.io/2016/09/introduction-return-type-declarations-php7/feed/ 1
A WordPress Developers Guide To Type Hinting In PHP 5 And 7 https://torquemag.io/2016/09/wordpress-developers-guide-type-hinting/ https://torquemag.io/2016/09/wordpress-developers-guide-type-hinting/#comments Tue, 06 Sep 2016 14:34:59 +0000 https://torquemag.io/?p=80069 PHP started out as a simple language without a lot of the conventions of other C-like programming languages that make them challenging to learn and more difficult to write. Over time, as PHP matured, many of those features have been added as optional syntax. One example of this type of feature is type hinting. Type hinting gives you the ability to define the type of values that can be passed for each argument of a function or method. Type hinting is optional, but when used it forces parameters to be a certain type or an error is thrown. Doing so makes […]

The post A WordPress Developers Guide To Type Hinting In PHP 5 And 7 appeared first on Torque.

]]>
PHP started out as a simple language without a lot of the conventions of other C-like programming languages that make them challenging to learn and more difficult to write. Over time, as PHP matured, many of those features have been added as optional syntax. One example of this type of feature is type hinting.

Type hinting gives you the ability to define the type of values that can be passed for each argument of a function or method. Type hinting is optional, but when used it forces parameters to be a certain type or an error is thrown. Doing so makes it more obvious what type of input a function expects but can also lead to more errors.

Type hinting is a feature of PHP that has only matured recently. In PHP 5 (as of 5.4) there are only four types of type hints that can be used, and these do not include scalar values — bool, float, int, and string. Scalar type hinting was introduced in PHP 7.

What Is A Type?

All variables have a type. For example, look at this variable declaration:

$x = 1;

We can now say that $x has the type “int,” which is short for integer. If we pass $x through var_dump() it will show us its type.

Some languages are “strongly typed,” which means that you have to declare a variable’s type before you create it. This is not true in PHP. Moreover, you can also change the type of a variable, which is why PHP is considered to be “dynamically typed.”

For example, this is totally legal:

$x = 1;
$x = array( 1 );

In other languages, this would throw an error for changing types. This is not the case, however, in PHP. Nor is it a problem is JavaScript, which is also dynamically typed.

Why Use Type Hinting?

Because PHP is a dynamically typed language, it is extremely flexible. It also means that we have to constantly check the contents of variables. For example, consider this function:

function slug_update_status( $post, $status ){
    if( is_numeric( $post ) ) {
        $post = get_post( $post );
    }

    if( ! is_object( $post ) ){
        return;
    }
    $post->post_status = $status;
    return wp_update_post( $post );

}

Most of this function ensures that the variable $post is actually an object. If an integer or string that can be interpreted as an integer is passed, then we try and make an object out of it using get_post().

We can rewrite this with type hinting to force the first argument to be a WP_Post object, which removes the necessity of checking that $post is an object.

function slug_update_status( WP_Post $post, $status ){
    $post->post_status = $status;
    return wp_update_post( $post );
}

Now, this function is shorter, has a single responsibility, and is more clear in its intent. The responsibility for ensuring that it is called with a valid post has shifted. Previously the responsibility for ensuring that we were only updating a valid post was on this function, which is not its actual purpose. Now the responsibility is on whatever code calls this function.

Why Not To Use Type Hinting?

The last paragraph of the previous section may have convinced you to use type hinting. That simple change made the code shorter and more concise, and the function now abides by the single responsibility principle, which is very important in software design.

There is a big difference between these two functions. If you ask yourself what happens if you pass a valid post ID to both, the difference becomes obvious. With the first function, you get the intended result and in the second you get a fatal error.

Ask yourself what happens if you pass an integer that does not correspond to a post to both functions.  In the first, nothing substantial happens. With the second function, you get a fatal error.

If you’re building a bespoke web application in PHP, with total unit test coverage, type hinting is really great. The fatal errors that they may cause are going to cause your tests to fail and give you an exact reason why.

For a WordPress plugin, theme, and site development, you have way less control over how your code is used. Not everyone using your code will know what to do with these errors, or will even know they will happen.

I’m not saying not to use type hinting if you are a WordPress plugin developer. Instead, I am saying that I think the flexibility of using dynamically typed languages is a huge part of why WordPress is so successful.

Types of Type Hints

In PHP 5, there are four types of type hints you can use. You can specify that a parameter is of a specific class or interface, is an array, is “self” or is callable. Let’s go through each of these, one by one.

Class Or Interface Type Hinting

Class or interface type hinting is useful and flexible. If you specify a specific class name as your hint, which is what I did in the last code example, then only an instance of that class or an instance of a subclass of that class will be accepted.

Let’s look at this function again:

function slug_update_status( WP_Post $post, $status ){
    $post->post_status = $status;
    return wp_update_post( $post );

}

The first argument has to be an instance of WP_Post or a subclass of it, so either of these two uses will work:

$post = get_post( 42 );

slug_update_status( $post, 'publish' );



$post = \WP_Post::get_instance( 42 );

slug_update_status( $post, 'publish' );

In both of these cases, $post is an instance of the WP_Post class. But, we can also use a subclass. That actually doesn’t apply with WP_Post since it can not be extended because it is defined with the final keyword.

But, if we had a function that was designed to create HTML markup from a WP_Query instance, we could pass it an instance of any class that extended WP_Query. In addition, we can also use interface names as our type hint, which provides a lot of flexibility as well.

Array Type Hinting

Type hinting as an array is, in my opinion, the most useful type hint in PHP5 for WordPress developers. We do a lot of array manipulation since WordPress developers tend to avoid creating specialized objects.

PHP and WordPress both provide a bunch of really helpful utility functions for working with arrays, but they all require an array be provided. If we can write a function or method that forces that an array be passed then we can use all of those utility functions safely.

When type hinting as an array, an empty array is a valid argument, but null is not. This example illustrates this:

function slug_flatten_to_json( array $array ){
    return wp_json_encode( array_values( $array ) );

}

//no error
$x = slug_flatten_to_json( [] );

//fatal error
$y = slug_flatten_to_json( null );

Because type hints are nullable, we could have avoided the fatal error by declaring the function like this:

function slug_flatten_to_json( array $array = null ){

But, while that would prevent the fatal error, we would still get a PHP warning because it would allow us to pass null to array_values(). In this example, that’s not good, but it may be useful in many cases.

Self Type Hints

Self type hints require a parameter of a class method — this does not work with functions out of object context — to be an instance of the same class the method is a part of. This is not a type hint typically used in a WordPress plugin or theme. Honestly, I can’t think of a practical use for it.

Callable Type Hints

A callable in PHP is any representation, as a string or array that can be used to call a function or string. Here are three examples of callables being used that should look very familiar to a WordPress developer should be familiar with:

add_action( 'wp_head', 'output_analytics' );

$analytics = new analytics();

add_action( 'wp_head', [  $analytics, 'get_code' ] );

add_action( 'wp_head', [ 'analytics_class', 'a_static_method' ] );

In the first example, we are using the name of a function — ‘output_analytics’ — stored in a string as a callable. In the second example, our callable is an array with an object and a string holding the name of a method of the class that object is an instance of. In the third example, the callable is in an array and references a static method of a class.

The WordPress Plugin API is powered by functions that accept callables — call_user_func() and call_user_func_array(). That is why if you don’t pass a valid callable to add_action() or add_filter() the error that is generated will be caused by one of those functions.

Errors caused by passing an invalid callback to add_filter() or add_action() are hard to debug as the errors are not very meaningful. Here is an example that would help avoid these errors and make the source of errors more obvious:

class plugins_api {
    static function add_action( $action, callable $callback ) {
        add_action( $action, $callback );
    }

    static function add_filter( $action, callable $callback ){
        add_filter( $action, $callback );
    }
}

Now if you pass an invalid callable then your error will tell you that this class generated it and what line, in what file called it. That is way easier to debug.

Scalar Type Hinting

One really cool feature of PHP7 is scalar type hinting. Scalar data types: strings, booleans, integers and floats can now be hinted.

The class I wrote as the example in the last section only solves one problem. While it forces the second argument of both methods to be a valid callable, it doesn’t prevent passing an invalid type — IE not a string — to the first argument.

In PHP7, we could rewrite this class like this:

class plugins_api {

    static function add_action( string $action, callable $callback ) {
        add_action( $action, $callback );
    }



  static function add_filter( string $action, callable $callback ){
         add_filter( $action, $callback );
  }

}

This rewrite makes it so that the first argument has to be a string. This isn’t a huge change, but again, it makes both methods clearer in their intent and makes errors caused by improper usage more obvious.

Do note, that in PHP5 this type hint would be interpreted as requiring the first argument to be an instance of the class “string” not a string. As a result in PHP5, passing a string to the class written this way would cause an error. In PHP7 a string is required.

There are three other types of scalar type hints: bool, int, and float. They can be used the same way as a string.

Just keep in mind that PHP is perfectly fine at dealing with being a dynamically typed language. When you try and use a number string, like “42,” as an integer, PHP will handle the conversion for you.

To Type Hint or Not To Type Hint?

In some ways, type hinting defeats the purpose of using a dynamically typed language. On the other hand, it’s good for clarity and performance. In PHP7, there is also return type declarations, which has similar advantages and disadvantages. PHP 7.1 might introduce property type declarations.

In many ways, these new language features are very exciting to me and I want to use them all of the time. That said, I do worry my code becomes overly pedantic and harder for other people to work with.

I’m not 100 percent sold on either side of this, but I do feel like everyone should understand these concepts. After all, it’s a free software and you can use it in any way that will compile. Since most of my work is in WordPress plugins for general release, I can’t use the PHP7 features and that limits the usefulness of type hinting for me. But, the code I do write in PHP7 is making heavy use of type hinting and return type declarations.

I hope this article has helped you understand this feature of the language. That way you will know what this syntax means and be excited for PHP7.

The post A WordPress Developers Guide To Type Hinting In PHP 5 And 7 appeared first on Torque.

]]>
https://torquemag.io/2016/09/wordpress-developers-guide-type-hinting/feed/ 6