Codementor Events

Learn a New Language: Migrating from JavaScript to PHP

Published Sep 30, 2016Last updated Jan 18, 2017
Learn a New Language: Migrating from JavaScript to PHP

Introduction

Once you've learned one programming language, it's usually easier to learn another—at least conceptually. It can get frustrating, however, when what works well in your first language doesn't work at all, or worse, works differently than you expect in your new language.

If you know JavaScript and HTML pretty well, but not PHP, this tutorial will help you migrate your existing JavaScript knowledge to PHP more easily. I will help you leverage what you already know by comparing important similarities and differences between the two languages.

Why learn PHP if you already know JavaScript?

There some tasks that are better suited for server-side execution. It's true that with the advent of Node.js, server-side JavaScript has become a reality. However, PHP still runs a lot of the web, especially WordPress—which drives over 25% of the web.

I've met a lot of front-end developers on Codementor who needed to make "a few small changes" in PHP to a WordPress theme, but didn't know PHP. They were usually frustrated because the apparent similarities between the two languages were more confusing than the obvious differences.

Even though Node.js is pushing JavaScript to the server, the fact is, JavaScript was designed from the beginning to run inside a browser—so it's primary strength is front-end work. PHP, on the other hand, was designed as a server-side language; and that is its primary strength.

Language Design: JavaScript vs. PHP

JavaScript was created by Brenden Eich in about 10 days while he was working for Netscape, to run in the Netscape browser. Its design was strongly influenced by Scheme, a dialect of LISP and Self, a dialect of SmallTalk. Very little of JavaScript is related Java. The JavaScript language standard is governed by ECMA.

JavaScript development has been driven largely by web browser companies. On the other hand, as a true Open Source project, PHP has had more community influence than JavaScript. It was originally designed for simple scripts for non-programmers. Some of the features that make it very forgiving for non-programmers are frustrating for experienced programmers. Whereas JavaScript borrows heavily from LISP and SmallTalk, PHP borrows heavily from PERL, C++, C and Java—and a smattering of other languages.

In my experience, the number one frustrating difference is: In Javascript the semi-colon character at the end of a line is more-or-less optional. In PHP, it's absolutely mandatory.

Getting Started

In JavaScript, you can have code within <script> </script> tags, or within a file with a .js extension. In PHP you need both the .php file extension and special tags to indicate PHP code.

The server treats .php files as if they were HTML files with special processing between the php tags. There are two ways to tag PHP code. The first, preferred way, is <?php ?>. The second way is shorter, but not supported by all servers: <? ?>.

Most servers require that PHP files have a .php extension. You will see two common coding patterns in PHP files. Files that are all, or mostly, PHP and HTML that contain a little PHP code.

Mostly PHP Code With a Little HTML

<?php
/**
* File: SomeFunctions.php
* Contains a bunch of PHP functions
*/
// This is a  PHP file with mostly PHP
function foo(){
    // This function outputs HTML in the middle
    // Some code
    // End PHP Tag
?>
<p>A little bit of HTML in the middle.</p>
<?php
   // Restart PHP
   // More Code
}

function bar() {
 // Some other PHP code
}
// No closing tag is necessary since there is no HTML below

HTML with Embedded PHP

<html>
<head>
<!-- index.php Acts just like index.html, but has a little PHP code embedded --->
</head>
<body>
<h1>The Time Is </h1>
<p>Server Time is: <?php echo date('H:i:s Y-m-d'); ?></p>
<!-- Prints time on the server in 00:00:00  YYYY-mm-dd format -->
</body>
</html>

Variables and Operators

The rules for naming, scoping, and operating on variables are a key part of any programming language. Understanding these key differences can go a long way toward clearing up any confusion you may have when you look at a PHP program through "JavaScript Eyes".

Naming Rules

PHP — variables in PHP must start with the dollar sign $ followed by the name of the variable. The variable name must start with either an underscore ( _ ) or a letter. The rest of the variable name can consist of letters, numbers, or underscores.

If a variable starts with two dollar signs, it's a dynamic variable. See below for an an example.

<?php
// Valid variables
$_ = 'A variable';
$a = 'Another variable.';
$b1 = 'Yet another variable';
$v = 'a';

// Dynamic Variables
// $$v refers to $a;
echo $$v; //  'Another variable.'
$v = 'b1';
echo $$v; //   'Yet another variable';

// Invalid Variables
$1a = 'Value'; // Error - cannot start with a number;
$a$b = 'Another Value'; //Error cannot contain a $, only start with one

?>

$ Is not jQuery

One of the points of confusion for some JavaScript programmers is that when they see a $ starting a variable name in PHP, they automatically think "jQuery". You just have to remind yourself that that's not the case. The $ in PHP has nothing to do with jQuery.

Global Scope

Global and local scoping are opposites in PHP and JavaScript. A common point of confusion for JS programmers migrating to PHP is that In JavasScript, any variable not explicitly local is global. In PHP any variable not explicitly global is local.

<?php
// The following variable is global because it is declared within the global scope.
$g = 'This is a global variable'; 

function foo() {
// The following variable is local by default;
   $g = 'This $g is local';
}

function bar() {
  global $g; // References the $g in global scope
  $g = 'I just changed the value of global $g'; 
}
?>

Operators, Strings, and Loose Data Types

Both PHP and JavaScript are loosely typed languages that attempt to allow automatic translation between strings and numbers.

One point of confusion between JavaScript and PHP is the string concatenation operator. In JavaScript, the plus sign, ( + ), is used for both arithmetic addition and string concatenation. In PHP, however, the dot ( . ) is used a string concatenation operator. Oftentimes, JavaScript programmers will mistake the string concatenation operator for an object dot notation.

In JavaScript, either single quotes ( ' ) or double quotes ( " ) can be used to indicate a string literal, and either is equally acceptable. In PHP that is almost, but not quite the same. In PHP, the double quoted string is used for variable substitution.

The comments next to the code below show the expected output of the various operators.

<?php

$b = '1';
$a = '2';

echo "$b $a"; // 1 2
echo '$b $a'; // $b $a
echo $b . $a; // 12
echo $b + $a; // 3

?>

Objects and Arrays

At first glance, the approach to arrays and objects appear similar in JavaScript and PHP. These apparent similarities can initially be a problem for JavaScript programmers migrating to PHP, who may assume that because they look alike they behave the same way.

PHP has two types of arrays: indexed and associative. These arrays can be multidimensional. PHP also has classes and objects. Arrays and objects are not interchangeable in PHP.

Compare this to JavaScript which has Arrays that are indexed numerically, and Objects which have properties and values. Object properties can be addressed using an array notation, giving the appearance of being associative arrays.

The fact that there are several different ways to declare an array in PHP can also be confusing. When dealing with arrays, it's important to be aware of which version of PHP is running on the server. Array declaration in PHP 5.4 and after can look more like JavaScript array declaration.

PHP Array Declaration Examples

<?php
// The following ways to declare arrays all do the same thing.

// Associative arrays:
$a['key1'] = 'Value1';
$a['key2'] = 'Value2';

// Identical results to above:
$a = array('key1' => 'Value1', 'key2'=>'Value2');

// For PHP version 5.4 and beyond:
$a = ['key1'=>'Value1', 'key2'=>'Value2'];

echo $a['key1']; // Value1

// Indexed Arrays use a zero based index
$a = array(); // Empty Array
$a[] = 'position 0'; // Empty [] appends to array
$a[] = 'position 1';

// The following does the same thing:
$a = array('position 0', 'position 1');

// Version 5.4 and after:
$a = ['position 0', 'position 1'];

echo $a[1]; // position 1

/*
Consider the following matrix:
     |col1            | col2
row1 | Cell Value 1,1 | Cell Value 1,2
row2 | Cell Value 2,1 | Cell Value 2,2
*/
// Multidimensional are "arrays of arrays" and can be declared using any valid array declaration syntax combination:

$m['row1']['col1'] = 'Cell Value 1,1';
$m['row1']['col2'] = 'Cell Value 1,2';
$m['row2'] = array('col1'=>'Cell Value 2,1', 'col2'=>'Cell Value 2,2'); 

echo $m['row1']['col1'];  // Cell Value 1,1
echo $m['row2']['col2']; // Cell Value 2,2


?>

The syntax to iterate across an associative array, using foreach looks a little different than the equivalent iterator in JavaScript.

<?php
// Using foreach to iterate over multidimensional  array $m from the previous example:

foreach($m as $row_key => $row) {
    foreach($row as $col_key => $cell) {
    echo "$row_key, $col_key: $cell<br/>";
    }
}
/*
Output:
row1, col1: Cell Value 1,1
row1, col2: Cell Value 1,2
row2, col1: Cell Value 2,1
row2, col2: Cell Value 2,2
*/
?>

Object Oriented Differences

JavaScript and PHP take a fundamentally different approach to object-oriented programming. Sometimes, these difference cause quite a bit of consternation to JavaScript developers. Because the OOP approaches in JavaScript and PHP are so fundamentally different, we will only touch certain key differences in this tutorial. I would encourage you to explore classes and objects in PHP further.

In PHP, Objects are distinctly different from associative arrays. The single most obvious difference between objects in JavaScript and PHP is the property access syntax. JavaScript uses "dot notation" to access object properties, whereas PHP uses the "pointer notation" to access object properties. The following code shows different object property access examples:

<script>
// Assume we have an object called "obj" with a property called "prop"
console.log(obj.prop); // Logs the value of the property to the console.
console.log(obj['prop']); // Same result
</script>

<?php
// Assume we have an object called "$obj" with a "property called "prop"
echo $obj->prop; // Prints the value of the property
// Example of dynamic property:
$v = 'prop';
echo $obj->$v; // Same result

// Common mistakes trying to use Javascript like syntax:
echo $obj.prop; // ERROR!!!
echo $obj['prop']; // ERROR!!!
?>

Property Visibility

In JavaScript all properties are public and available to be read or modified by any part of the program at any time. Certain coding conventions can be used to indicate the intent that a property is private, but the language does not enforce it. In PHP, properties are public by default, but can be declared otherwise.

JavaScript uses the "Everything is an Object" approach to OOP. In PHP, classes define what an object can be. Objects are instances of classes.

<?php
class BaseClass {
    $public_prop1; // Public by default;
    public $public_prop2; // Explicitly public
    protected $protected_property; // Available to this class and its subclasses
    private $private_property;  // Available only to this class

    function set_private_property($value) {
        $this->private_property = $value;
    }
   protected function get_the_private_value() {
       return $this->private_property;
   }
}

$obj1 = new BaseClass();  // An object is an instance of a class
echo $obj1->public_prop1; // OK
echo $obj1->public_prop2;// OK
$obj1->set_private_property('something'); // OK
echo $obj1->protected_property; // Access error
echo $obj1->private_property; // Access error;
echo $obj1->get_the_private_value(); // Access error

?>

Inheritance

JavaScript uses prototype-based inheritance to make copies of objects as an inheritance mechanism. PHP, on the other hand, uses class-based inheritance. The code below shows an example of how class-based inheritance works in PHP.

<?php

// SubClass inherits from BaseClass from the example above.
class SubClass extends BaseClass {
     function get_protected() {
         return $this->protected_property; // OK (uses protected base class property)
     }
    function get_private_ok() {
        return $this->get_the_private_value(); // OK (uses protected base class method)
    }

   function get_private_error() {
       return $this->private_property; // Access Error: Cannot directly access private value from a base class.
   }
}

?>

JSON

JSON is the De-facto standard mechanism for transferring objects. If you are a JavaScript programmer using PHP, you will almost certainly be passing objects back and forth in JSON format.

<?php
    $json = $_POST['json']; // Get a JSON string submitted from a POST (perhaps via ajax)
    $obj = json_decode($json); // Turn the JSON string into a PHP object.
    $arr = json_decode($json, true); // Turn the JSON string into a PHP associative array.

   // Use the base class from above.
   // Only the public variables are encoded, not the private or protected properties.
   $obj  = new BaseClass();
   $json = json_encode($obj);
   // {"public_prop1":null, "public_prop2":null }
   // The properties are null because they were never initialized.
    
?>

Control Structures

The control structures in PHP can be very similar to the control structures in JavaScript. However, in PHP, there are more variations. For example, keywords and function names in PHP are case-insensitive. There are also multiple ways to express they same control structure.

The following code shows examples of common PHP control structures.

If/Then/Else

$a = 1;
$b = '1';

// Type insensitive compare
if ($a == $b) {
 // This code will execute
} else {
// This code will not
}

// Alternative structure
IF  ($a === $b) : // Type sensitive compare.  IF keyword case insensitive;
   // This code will not execute
else:
  // This code will execute
ENDif; // The endif keyword is not case sensitive

While
Like the if statements, the while loop can be similar to JavaScript, but there are alternative syntax options.

$c = 10;
$d = 0;

//Typical while syntax - very similar to JavaScript
while( $d < $c) {
  $d++; 
}

// Alternative while syntax - also demonstrates case insensitivity
while ($c === $d) :
   $c++;
EndWhile;

For Loops

You've already seen the foreach construct in action with the array iterators above. Like JavaScript, PHP also has a for loop control structure. And, it also has an alternative syntax.

// Typical For Loop
for ($i = 0; $i < 100; $i++) {
  // Execute this code 100 times;
}

// Alternative for loop
for ($i = 0; $i < 10; $i++ :
   // Execute this code 10 times;
endfor;

Like JavaScript, PHP also has a switch control structure which follows a similar pattern to the examples above.

Functions

Probably the closest point of similarity between PHP and JavaScript is the way functions work. Like JavaScript, PHP functions begin with the keyword function . And like JavaScript, in PHP, functions can be named, anonymous, nested, and recursive.

The examples below will probably seem familiar to JavaScript programmers

<?php
// Simple function:
function add_one($v) {
   return $v + 1;
}

// Recursive function:
function recursion($a) {
    if ($a < 20) {
        echo "$a\n";
        recursion($a + 1);
    }
}

// Nested function
function foo() 
{
  function bar() 
  {
    echo "I don't exist until foo() is called.\n";
  }
}

/* We can't call bar() yet   since it doesn't exist. */

foo();

/* Now we can call bar(), foo()'s processing has made it accessible. */

bar();

// Anonymous Function
$greet = function($name) {
    echo 'Hello ' . $name;
};

$greet('World');
//  Hello World

?>

Summary

If you know JavaScript and HTML, but not PHP, we've shown you some ways to help you migrate your existing JavaScript knowledge to PHP more easily. You have been able to compare important similarities and differences between the two languages.

The major differences include: the mandatory use of the semi-colon at the end of a statement, the way variables are named and scoped, and the way objects and arrays are built and referenced and the alternative syntax for control structures.

The major similarities include the standard control structures, comparison operators, and how functions are defined and used.

If you need more help, feel free to contact me or another full stack developer here on CodeMentor with expertise in both PHP and JavaScript.

Discover and read more posts from David Brumbaugh
get started
post commentsBe the first to share your opinion
Show more replies