PHP Advanced Guide | Exploring the Path to High-Level Learning Resources
Unlike other programming languages that boast a wealth of resources, there are scarcely any deep-dive materials for PHP nowadays.
The resources I’ve compiled here are not meant for beginners; they don’t cover basic programming concepts. Instead, they delve straight into PHP’s unique aspects and recommend some high-quality learning resources.
First off, setting up a local development environment is essential
Even if you don’t plan on using major frameworks like Symfony or Laravel… By establishing an environment capable of running these frameworks, you’ll have everything most PHP development requires, including:
PHP — The programming language
MySQL — The database
NGINX or Apache — The web server
Composer — PHP’s package manager
Prefer virtual machines? Homestead is tailor-made for PHP development.
Fancy Docker? Give these a try:
Already have or want a local web server?
XAMPP is among the most popular solutions. It’s an Apache distribution that includes MariaDB and PHP.
If you’ve already got Apache or NGINX locally installed and prefer developing locally without a VM — you can directly install PHP and its most popular extensions. Here are the commands to install PHP on Ubuntu (Linux):
sudo add-apt-repository -y ppa:ondrej/php
sudo apt-get update
sudo apt install -y php7.4 php7.4-common php7.4-cli php7.4-fpm libapache2-mod-php7.4 php-pear php7.4-bcmath php7.4-bz2 php7.4-curl php7.4-dev php7.4-gd php7.4-intl php-gettext php7.4-json php7.4-mbstring php7.4-mysql php7.4-opcache php7.4-readline php7.4-soap php7.4-sqlite3 php-xdebug php7.4-xml php7.4-xmlrpc php7.4-zip
On Windows, many developers opt for WAMP. You can also install it using WSL (Windows Subsystem for Linux) or follow the Windows installation guide in the official PHP manual. Switching to WSL2 means Windows users can more or less follow the Linux guide. Laragon is another development environment suitable for Windows.
Mac users often go for ServBay.
As a Mac user, I use ServBay, a more convenient local environment that takes less than 5 minutes to set up, and integrates databases and other tools with a high degree of customization. I suggest exploring these options on your own, as I won’t delve further into them.
Windows: https://dev.to/bantar7/how-to-install-and-configure-xampp-on-windows-2c23
Give it a try
When you can run:
php -v
and see the PHP version info, you’re set.
PHP has a built-in command-line interactive mode, allowing you to input and run PHP commands for testing. Enter:
php -a
It gives you a prompt where you can input lines of PHP code, which run and display output upon hitting Enter. If you like using such a feature, I recommend PsySH, which does the same but better.
You can run a PHP file from the command line like this:
php index.php
PHP also has a built-in web server, which you can use instead of installing Apache or NGINX. It’s great for quick testing. In fact, much of my development work uses this built-in web server and locally installed MySQL. I have Apache, but often I don’t need it. Run the built-in web server in a directory containing .php files like this:
php -S
This starts the web server, listening on the given host and port. Then, if you visit http://localhost:8000/ in your browser, you can execute the PHP applications present in that directory.
Note, the index.php file is the entry point for most PHP applications. The URL mentioned above will default to invoking index.php.
PHP Language Overview
PHP is an interpreted language, meaning your PHP program isn’t compiled ahead of time. When a browser requests a PHP resource (usually a .php file) from a web server, the server provides all details of the request (like URL GET parameters, POST values, cookies, header information, etc.) to the PHP interpreter, which executes the requested PHP file. If you edit a PHP file on the server, that change takes effect immediately.
Most of the time, the index.php file is the entry point for PHP applications, usually performing some bootstrap operations and executing a framework to handle the request values, often packaged in a Request object. Older applications might not use a Request object; in those cases, values in the request can be found in the $_GET, $_POST, $_COOKIE, $_SERVER
super global arrays, accessible anywhere in the application. Modern frameworks place these values into a Request object and then clear those superglobals to avoid the pitfalls of global variables. As the PHP program executes, output is returned to the browser. Some programs use echo() statements and similar commands to send output temporarily, which sends the output to the standard output stream (back to the web server, then to the browser...or to the command line). Modern applications collect all output into a Response object, then send it to the browser all at once (one of the last few steps of the framework).
By default, PHP is stateless. All variables, objects, and connections created during a request’s execution aren’t preserved for the next request. PHP clears the memory used during that request and knows nothing from one request to the next. Multiple requests coming into the server can be executed concurrently.
PHP developers use mechanisms to maintain some memory or state between requests. The most common method is sessions. PHP sends a session ID value to the browser, usually stored in a cookie. The browser sends this ID back with all future requests. PHP uses that ID to find values associated with that ID stored in the filesystem or database (or in data stores like Redis or Memcached). In this way, PHP can “remember” a visitor between requests. However, values in these session stores must be read from the data store in each request. They’re stored in a superglobal variable called $_SESSION,accessible from the application.Many frameworks put this superglobal into their own Session object.
Here′s a great article on how PHP applications work(https://carlalexander.ca/php-application/)), including topics on concurrency and multitasking in PHP.
PHP Types
PHP is a dynamic, weakly−typed language. Variables aren′t defined with types (nor can they be), but instead, their types are inferred from the values assigned to them, and the type can change if a new value is assigned.
$something = 1; // Weakly typed as an integer.
$something = "Hello"; // Now it's a string.
This means you′ll find a lot of type checking and conversion in PHP programs:
$age = intval($age); // Make sure $age is an integer.
if( is_int($age) ){
// Do something.
}
Such coercions and checks are very common in PHP applications. Since all values passed to PHP from browser requests are strings, PHP programs often convert these values to the expected type.
In recent years, PHP has added strict typing features. This means function and method parameters can explicitly set types for incoming arguments, and return types. If the incoming value is not the expected type, a runtime exception is thrown. If you see this directive:
declare(strict_types=1);
At the top of a file, then the types in that file are considered strict. This means the strictness of types can vary from file to file within an application. This allows large applications to migrate to strict types one file at a time.
For example:
declare(strict_types=1);
function doSomething(int $id): string {
$id = '' . $id;
// This is allowed in PHP: $id is a string now.
}
doSomething('1'); // This would trigger a TypeError.
doSomething(1); // This would be fine.
A ?
before a type indicates that the value is nullable (it can also be null).
The type system in PHP can be a source of confusion or errors. The code should be very clear about what type a variable is at any time and how it can change. Many recommend using strict types as much as possible.
More on types in PHP:
PHP Arrays — Learn to Love Them
One of the most common data structure types in PHP is arrays. PHP developers use arrays for a variety of things — often in place of data objects, which may not be the best idea! Arrays in PHP are very flexible because they are actually hash maps. This means array keys don’t have to be sequential, or even numeric. Populating an array with non-sequential integer indices doesn’t mean all units between those array cells are preserved:
$houses[0] = 'Blue';
$houses[55] = 'Red';
printf( array_key_exists(8, $houses) ); // 0 (false)
Array keys can be strings:
$config['username'] = 'tonystark';
$config['password'] = 'ironman123';
// This can also be defined like so:
$config = ['username' => 'tonystark', 'password' => 'ironman123'];
You can also declare a value as an empty array ahead of time, or you can assign many values, and they will be given sequential, numeric keys starting from 0:
$superheros = array(); // empty array.
$superheros = array('Superman', 'Batman', 'Black Widow', 'Ironman');
print_r($superheros); // [0] => Superman, [1] => Batman ...etc
All keys in a PHP array don’t even have to be the same type! There’s a lot of documentation on arrays at PHP.net, and PHP provides many built-in functions for sorting and manipulating arrays.
PHP Syntax
PHP’s syntax is somewhat related to C. Some highlights:
All variables start with
$
. Class names, method names, and function names do not.All statements end with a semicolon
;
.Control structures are enclosed in braces
{}
.Whitespace and indentation are not significant.
PHP code starts with
<?php
(sometimes abbreviated to<?
) and ends with?>
. This code can be intermixed with regular HTML...but modern applications no longer do this. If a file ends with PHP code, the closing tag is omitted.Strings can be enclosed in either single quotes or double quotes. Special characters (like
\n
for a newline) are only recognized within double quotes.Many projects have a coding standard guide or a loose policy to keep things consistent. For example, class names start with a capital letter.
Code Analysis
The PHP community has created many excellent tools that allow you to analyze the style, quality, and even correctness of PHP code. These static analysis tools are valuable for keeping a project following a set of coding styles or finding code smells in an application. While there are many PHP analysis tools to choose from, some popular ones include:
Autoloading and Composer
If your PHP application’s entry point is the index.php file…unless they are included into the requested file, other source code files won’t run or be referenced. So if you run a file “test.php”, only the code in that file will be available. Historically, projects would use several include or require statements to bring in other code:
<?php
// File index.php
require('config.php'); // Execution will stop if this file is not found.
include('functions.php'); // If the file isn't found, execution continues anyway.
require_once('user.php'); // Ensure this isn't included multiple times.
$foo = 'bar';
You might see many includes like the above at the top of an index.php file, bringing in class definitions, functions, etc., needed by the application.
Modern PHP applications no longer use such includes. Composer is PHP’s package manager. It also provides an autoloader, which automatically includes class (object definition) files, only doing so when the application needs them. This prevents including code that is never used. Configuring Composer in a project creates a vendor/
directory, which will house the autoloader and any installed packages. If you see a vendor directory or a composer.json file at the root of a project, that's how you know Composer is being used. Don't be surprised if many older applications don't use it. PEAR is an older system for installing packages into PHP projects.
In the case of using Composer’s autoloader, you’ll see this at the top of every file in the application:
require_once 'vendor/autoload.php';
Composer allows us to bring in dependencies (like open-source projects found on Packagist), which will be installed in the vendor directory, immediately available for our project’s use. We can pin them to certain version numbers, update our dependencies, and declare some packages only for use in a development environment (like testing and static analysis tools).
Understanding and learning Composer is highly relevant to modern PHP development. An introduction to Composer is here:
https://getcomposer.org/doc/00-intro.md
PHP Resources and Looking Forward
PHP is a language with a lot of history, and the tutorials, StackOverflow answers, and blog posts you might find online about PHP can be very outdated and contain many security vulnerabilities. I recommend not using resources or code that are more than 3 years old.
PHP versions have a defined lifecycle. Make sure you’re using a supported version.
PHP has one of the best official documentations, including examples and user-contributed comments. The official documentation is at https://www.php.net/.
The official publication (magazine) for PHP is php[architect].
There’s a lot of high-quality targeted information here. One of the top resources for learning modern PHP is the website https://phptherightway.com/.
Here’s a list of a bunch of useful resources:
https://odan.github.io/learn-php/
Enjoy Your Journey
Today, PHP is a modern, flexible, and popular programming language. The community is vast and inclusive, with a rich and diverse array of resources about PHP. I enjoy using PHP, and with ongoing core updates and new versions, it keeps getting better. PHP 8 has just been released. Welcome to the world of PHP