DEV Community

Cover image for Learn PHP For Experienced Developers
SyntaxSeed (Sherri W)
SyntaxSeed (Sherri W)

Posted on • Edited on • Originally published at blog.syntaxseed.com

Learn PHP For Experienced Developers

In my efforts to help a colleague, I discovered that there are few resources for people who are already programmers in other languages to learn PHP. Something that isn't beginner level, doesn't explain basic programming concepts... just get to the heart of what makes PHP unique, and some suggested quality resources to learn more.

This is what I've written here. It's a high-level overview of the language, and some vetted resources to get set up and learn more.

Let's get started...

Set Up A Local Dev Environment

Even if you aren't going to be using a major framework like Symfony or Laravel... if you set up an environment that can run these frameworks, you'll have everything you'll likely need for most PHP development. These usually include:

  • PHP – the language runtime
  • MySQL – database
  • NGINX or Apache – web server
  • Composer – PHP's package manager

Do you like VMs? Use the excellent Vagrant box customized for PHP development called Homestead. (I have used this myself.)

Like Docker? Try:

Have/want a local webserver?

XAMPP is one of the most popular solutions. It is a distribution of Apache with MariaDB & PHP included.

If you already have Apache or NGINX installed locally and like to do local development without a virtual machine – you can install PHP and it's most popular extensions directly. These are the commands I use on Ubuntu (Linux) to install PHP:

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
Enter fullscreen mode Exit fullscreen mode

On Windows, many developers use WAMP. You can also install it directly using WSL (Windows Subsystem For Linux) or use the Windows install guide in the official PHP manual. The move to WSL2 means Windows users can more or less follow Linux guides. Laragon is another dev environment for Windows.

Users on Mac often use MAMP.

For myself, I work on a Ubuntu machine and I have PHP, MySQL & Apache installed directly.

These are some excellent guides for setting up a local environment:

Try It Out

You'll know you're ready to roll when you can run:

php -v
Enter fullscreen mode Exit fullscreen mode

on a command line and see the PHP version info.

PHP has a built in command line interactive mode which lets you type and run PHP commands to try things out. Type:

php -a
Enter fullscreen mode Exit fullscreen mode

It will give you a prompt where you can enter lines of PHP code and when you hit enter it will run those lines and show the output. If you like using something like this, I recommend the more advanced PsySH which does the same thing but much nicer.

You can run a PHP file from the command line like so:

php index.php
Enter fullscreen mode Exit fullscreen mode

PHP also has a built-in web server that you can use instead of having Apache or NGINX installed. This is nice for quick testing. In fact much of my development uses this built in web server and a local installation of MySQL. I have Apache but often don't need it. Run the built-in web server within a directory that has .php files like so:

php -S localhost:8000
Enter fullscreen mode Exit fullscreen mode

This will start up the web server listening on the given host and port. Then if you visit http://localhost:8000/ in your browser you can execute your PHP application that exists in that directory.

Note that the index.php file is the entry point for most PHP applications. The URL above will call index.php by default.

PHP Language Overview

PHP is an interpreted language meaning that your PHP programs are not compiled ahead of time. When a browser makes a request to a web server for a PHP resource (usually a .php file) the web server provides all the details of the request (for example the URL GET parameters, POST values, cookies, headers, etc) to the PHP interpreter which executes the requested PHP file. If you edit a PHP file on the server, that change will take place immediately.

Most of the time the index.php file is the entry point to a PHP application and it usually performs some bootstrapping and executes the framework to handle the request values which are often packaged together into a Request object. Older applications might not use a Request object, in that case the values from the request can be found in $_GET, $_POST, $_COOKIE, $_SERVER super global arrays which are accessible from anywhere in an application. Modern frameworks place these into a Request object then wipe out those super global values to prevent pitfalls of global variables.

As the PHP program executes, the output is returned to the browser. Some programs send output in an ad hoc manner using echo() statements and similar commands which send output to the standard output stream (back to the web server which sends it to the browser... or to the command line). Modern applications gather all output into a Response object which is sent to the browser all at once at the end of the program's execution (one of the framework's final steps).

PHP is stateless by default. All variables, objects, and connections created when the program executes for a request, are not retained for the next request. PHP clears the memory used during that request and doesn't know anything between one request to the next. Multiple requests coming into a server can be executed concurrently.

There are mechanisms that PHP developers use to maintain some memory or state between requests. The most common method is Sessions. PHP sends the browser a session ID value which is usually stored in a cookie. The browser sends back this ID with all future requests. PHP uses that ID to look up values stored on the filesystem or in a database (or a data store like Redis or Memcached) that are associated with that ID. In this way PHP can ‘remember' the visitor between requests. However these values in the Session storage must be read from the data store on every request. They are saved in a super global called $_SESSION which can be accessed from within the application. Many frameworks place this super global into their own Session object.

This is a good article (https://carlalexander.ca/php-application/) about how PHP works including topics about concurrency and multitasking in PHP.

Types In PHP

PHP is a dynamic, weakly typed language. Variables are not defined with a type (and cannot be), instead the type is inferred by what is assigned to it and can change if something new is assigned.

$something = 1;  // Weakly typed as an integer.
$something = "Hello";  // Now it's a string.
Enter fullscreen mode Exit fullscreen mode

This means that you will find a lot of type checking and casting in PHP programs:

$age = intval($age);  // Make sure $age is an integer.

if( is_int($age) ){
    // Do something.
}
Enter fullscreen mode Exit fullscreen mode

The above sorts of forcing and checking of types are very common in PHP applications. Since all values passed to PHP in the request from the browser are strings, PHP programs will often cast these values to the types expected.

In recent years, PHP has added strict typing features. This means function and method parameters can explicitly set a type for the incoming parameters and return types. A runtime exception will be thrown if the incoming value is not the expected type. If you see this directive:

declare(strict_types=1);
Enter fullscreen mode Exit fullscreen mode

At the top of a file, then the types in that file will be treated as strict. This means that type strictness in files may differ. This enables 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.
Enter fullscreen mode Exit fullscreen mode

A ? in front of a type means that value is nullable (it can also be null).

PHP's type system can be a source of confusion or errors. Code should be highly aware of what type a variable is at any given time and that it can change. Many people recommend the use of strict types where possible.

More info about types in PHP:

PHP Arrays – Learn To Love Them

One of the most common types of data structure in PHP is arrays. PHP developers use arrays for all kinds of things – often in place of data objects which might not be the best idea! Arrays in PHP are very flexible because they are actually hashmaps. This means the array key does not have to be sequential or even numeric. Filling an array with disconnected integer indexes does not mean that all the array cells between will be reserved:

$houses[0] = 'Blue';
$houses[55] = 'Red';
printf( array_key_exists(8, $houses) ); // 0 (false)
Enter fullscreen mode Exit fullscreen mode

Array keys can be strings:

$config['username'] = 'tonystark';
$config['password'] = 'ironman123';

// This can also be defined like so:

$config = ['username' => 'tonystark', 'password' => 'ironman123'];
Enter fullscreen mode Exit fullscreen mode

You can also declare a value as an empty array ahead of time, or you can assign many values which will be given sequential, numeric keys starting at 0:

$superheros = array(); // empty array.

$superheros = array('Superman', 'Batman', 'Black Widow', 'Ironman');
print_r($superheros); // [0] => Superman, [1] => Batman ...etc
Enter fullscreen mode Exit fullscreen mode

All of the keys in a PHP array don't even have to be the same type! PHP.net has a lot of documentation about arrays and PHP provides many built in functions for sorting and manipulating arrays.

PHP Syntax

PHP's syntax is slightly related to C. Some highlights:

  • All variables begin with a $. Class names, method and function names do not.
  • All statements end with a ;.
  • Control structures are wrapped in curly braces {}.
  • White space and indenting does not matter.
  • PHP code begins with <?php (sometimes just <? for short) and ends with a ?>. This code can be interspersed in regular HTML... but modern applications don't do that anymore. If a file ends with PHP code, the closing tag is left off.
  • Strings can be wrapped in single or double quotes. Special characters (like \n for a newline) will only be recognized in double quotes.
  • Many projects have a coding standards guide or loose policy to keep things consistent. For example, class names begin with a capital.

This article gives a quick overview of PHP syntax:

Code Analysis

The PHP community has created many excellent tools which enable you to perform analysis on the style, quality, and even correctness of your PHP code. These static analysis tools can be valuable to help keep your projects on a set coding style, or to find code smells in your application. While there are many PHP analysis tools to choose from, some popular ones are:

Autoloading and Composer

If your PHP application entry point is the index.php file... no other files of source code will be run or referenced unless they are included into the requested file. 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 other code in:

<?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';
Enter fullscreen mode Exit fullscreen mode

You may see many includes like the above at the top of an index.php file which will bring in class definitions, functions, etc which are needed by the application.

Modern PHP applications don't use includes like this anymore. Composer is the package manager for PHP. It also provides an autoloader which will include class (object definition) files automatically, only once they are needed by the application. This prevents including code that is never used. Composer when configured in a project creates a vendor/ directory where it will place 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 can tell that Composer is being used. Don't be surprised if many older applications don't use it. PEAR is an older system used to install packages into PHP projects.

In the case of Composer autoloading being used, you will see this at the top of every file in an application:

require_once 'vendor/autoload.php';
Enter fullscreen mode Exit fullscreen mode

Composer lets us pull in dependencies (like the open source projects found on Packagist) and they will be installed in the vendor directory and become instantly available to our projects. We can pin them to certain version numbers, update our dependencies and declare some packages to be for the dev environment only (like testing and static analysis tools).

Understanding and learning Composer is very relevant for modern PHP development. An intro to Composer is found here: https://getcomposer.org/doc/00-intro.md.

PHP Resources & Looking Ahead

PHP is a very old language and the tutorials, StackOverflow answers, and blog posts about PHP that you might find online can be very outdated and include many security flaws. I recommend not using resources or code from over 3 years ago.

PHP's versions have a defined lifecycle. Make sure you are using a supported version.

PHP has some of the best official documentation around, including examples and user-contributed comments. The official docs are found at https://www.php.net/.

The official publication (magazine) for PHP is php[architect]. I've had a subscription for several years and sometimes write for the magazine. A lot of high-quality targeted information in here.

One of the top resources for learning modern PHP is the website https://phptherightway.com/.

The following is a large list of useful resources:

https://odan.github.io/learn-php/.

The website https://laracasts.com/ is full of very high quality PHP and web development tutorials. Many are specific to the Laravel framework, but there are also many that cover PHP in general and modern best practises. I love this resource so much, that despite not using Laravel, I have a lifetime subscription to LaraCasts. Suggested series:

There is a similar screencasts website for the other top PHP framework, Symfony (the one I use) found at https://symfonycasts.com/.

The most popular editors for PHP are VSCode (what I use) & SublimeText. If you prefer a full IDE, the best is PHPStorm, but it is a commercial product.

Enjoy Your Journey

Today, PHP is a modern, flexible, popular programming language. The community is very large and welcoming, and the wealth of resources about PHP is vast and varied. I enjoy using PHP and the language continues to receive core updates and new versions which just keep getting better. PHP 8 was released very recently. Welcome to PHP and thanks for reading!

--
Originally Published on Blog.SyntaxSeed.com

Top comments (10)

Collapse
 
hikarimaeda profile image
Hikari

A tool called ServBay is catching on. It seems that it could help developers deploy the environment within 3 minutes.
Does anyone hear of this?

Collapse
 
alecbsherman profile image
Alec

I've been using PHP for about 10 years. Excellent article.
You listed 5 PHP analysis tools - which of them would you recommend as your favorite?

Collapse
 
leslieeeee profile image
Leslie

If you are a macOS user, ServBay.dev is worth to try. You don't need to spend some time or couple of days to setup anything. Just download it and you can use it immediately. You can run multiple PHP versions simultaneously and switch between them effortlessly.
Honestly, this tool has greatly simplified my PHP development and is definitely worth trying!

Collapse
 
nicolasperego profile image
NicolasPerego

Thanx a lot. You made me save precious time!

Collapse
 
arvindsridharan profile image
arvindsridharan

Thank you for compiling resources on Php.

Collapse
 
derryyeh profile image
Derrr

Really appreciate it!

Collapse
 
abdullahkhanpwd profile image
abdullahkhanPWD

I like your way of tutoring. Thank You. Hope so You will post more relevant to php towards Laravel.

Collapse
 
nuwara profile image
nuwara

Thank you for this comprehensive guide to PHP.

Collapse
 
iamak profile image
Ajithkumar P S

Really good article👌

Collapse
 
fullfull567 profile image
fullfull567

Hey there! It seems a bit complex for me at the moment. Could you please suggest some simpler solutions or perhaps break down the steps for beginners like me? I'd really appreciate your help!