DEV Community

Megan Miller
Megan Miller

Posted on • Edited on

PHP For JavaScript Developers

I started learning how to code in 2012 with HTML and CSS. Ever since the start of my coding journey, PHP has been one of the languages I’ve always wanted to learn. It’s everywhere. However, looking at it back in 2012, a freshly graduated high school student; I felt completely out of my depth. You can find out more about my journey here if you’re curious.

As a recent JavaScript-focused bootcamp grad, I’ve decided that I want to try to learn PHP again. It has been pretty difficult to find resources about PHP that aren’t focused on people who have never touched a line of code before. So, that’s why I’m writing this. I want to be able to help other people like me who just need a quick guide to the differences between their chosen language and the language they want to pick up.

General Syntax

One of the biggest differences between PHP’s syntax and JavaScript’s is that semicolons are required at the end of lines in PHP. I struggled with this a lot at first—still do sometimes—so that’s why I wanted to note it here first and foremost.

Using The Language

In JavaScript you don’t have to do anything particularly special to be able to run the code beyond making sure your file has a .js extension. However, in PHP you need to use tags, even in a file designated with the .php extension.

<?php 
# code here
?>
Enter fullscreen mode Exit fullscreen mode

Declaring Variables

Creating a variable in PHP is super simple. Much like JavaScript, PHP is a dynamically typed language, and as such you don’t have to declare the type of the variable when you create it. It uses the $ symbol to denote variables.

$myvar = 'value';
Enter fullscreen mode Exit fullscreen mode

By default in PHP any variable you declare is mutable. It can be changed absolutely anywhere.

Declaring Constants

PHP has a special function called define that is used to specifically create variables that can’t be changed. It takes two arguments: the name of the variable, and the value you want to assign to it. By default this function sets the variable name you create to be case sensitive. This can be overridden by passing true as a third argument to the function.

define('CONSTANT_NAME', value, true);
Enter fullscreen mode Exit fullscreen mode

Declaring Arrays

Much like JavaScript arrays can be created with standard bracket notation or with a function in PHP. That said, PHP’s associative array is equivalent to a JavaScript Object, and is the only way to create a collection of key/value pairs in PHP without importing a module of some kind. Assigning a value to a key in PHP is denoted by =>.

$myArray = ['key1' => 'value', 'key2' => 'value', 'key3' => 'value'];
Enter fullscreen mode Exit fullscreen mode

Functions
Functions in PHP are very similar to JavaScript (ES5 specifically).

function myFunc($param) {
    return $param;
}
Enter fullscreen mode Exit fullscreen mode

The only real difference I’ve been able to find between the two languages in this regard is that PHP has an operator that changes the argument you pass in from being value based, to being referential: the &.

$myVar = 10;
echo $myVar; # displays 10

function addTen(&$param) {
    return $param += 10;
}

addTen($myVar);

echo $myVar; # displays 20
Enter fullscreen mode Exit fullscreen mode

Loops

Much like Functions, loops aren’t that much different from the way they’re written in JavaScript. One exception being PHP’s foreach loop which changes based on the type of array you’re trying to loop over.

Normal Array:

foreach($arrayName as $item) {
    # do code
}
Enter fullscreen mode Exit fullscreen mode

Associative array:

foreach($myArray as $key => $value) {
    # do code
}
Enter fullscreen mode Exit fullscreen mode

Classes & OOP Methodology

Classes are one place where PHP differs from JavaScript quite heavily. Though PHP didn’t start out as an Object Oriented Programming Language—similarly to JavaScript—the functionality was added in later.

Access Modifier Keywords
In standard JS, modifier keywords aren’t needed for classes. For PHP, however, they are.

The Modifiers that you have in PHP are:

  • public - This can be used outside the class, either by a script or another class.
  • private - The class that created this is the only one that can access it.
  • protected - This can only be accessed outside of the class if it is being called in a class that is a child of the class this belongs to.
  • static - Allows the use of a property or method without the class that property or method is a part of having to be instantiated.

When creating a class in PHP it’s best practice to utilize these keywords to tell the class what it needs to do with attributes and methods on the class.

class MyClass {
    private $classAttrib;
    public function __construct($classAttrib) {
        this->classAttrib = $classAttrib;
    }
}
Enter fullscreen mode Exit fullscreen mode

You’ll notice a few things in the above the code snippet. The first will probably be the two modifier keywords. Here, we’re declaring a private variable called classAttrib which will only be accessible via MyClass. The second, is the public keyword which we’re using in conjunction with PHP’s built in __construct method. This allows us to instantiate a class as though it were a function, just like we would in JavaScript.

$myClass = new MyClass(someValue);
Enter fullscreen mode Exit fullscreen mode

This and The Arrow

Continuing with the MyClass example above, you’ll notice that we’re using this in the same way that we would in JavaScript. The difference here, is that we’re using an arrow (->) to access classAttrib on the class. We’ll also use this pointer to access anything on the class that we need to use throughout our code.

Here’s the same class in JavaScript:

class MyClass {
    constructor(classAttrib) {
        this.classAttrib = classAttrib;
    }
}
Enter fullscreen mode Exit fullscreen mode

Getters and Setters
Getters and Setters are class methods used to get and set (or update) information to do with the class attributes. In JavaScript we don’t typically need to make them, and similarly they aren’t required in PHP. That said, you’ll see them far more frequently in PHP, so I thought it would be prudent to go over here. Basically, these methods are the only things that should be directly modifying or otherwise interacting with the class attributes outside of the class.

# ... inside MyClass
    public function setClassAttrib($classAttrib) {
        return $this->classAttrib = $classAttrib;
    }

    public function getClassAttrib() {
        return $this->classAttrib;  
    }
Enter fullscreen mode Exit fullscreen mode

Inheritance
Inheriting from parent classes in PHP is similar to JavaScript, with the exception being that we don’t use super to pass in the parent class’ attributes. Instead we use the :: operator. Also called the Scope Resolution Operator.

class SecondClass extends MyClass {
    private $newAttrib;
    public function __construct($classAttrib, $newAttrib) {
        parent::__construct($classAttrib);
        this->newAttrib = $newAttrib;
    }
}
Enter fullscreen mode Exit fullscreen mode

PHP & JavaScript Similarities

Now that we’ve talked about a fair few of the differences between JavaScript and PHP, let’s talk about some similarities!

  • PHP has spread syntax! You can use the exact same syntax as in JavaScript, in both arguments (argument unpacking is available in PHP 5.6+) and arrays (available from PHP 7.4+)!
  • PHP has ternaries!
  • PHP has type coercion with the ==!

As I mentioned earlier, I'm still new to PHP, but I hope that this article was helpful to you! ❤️

Top comments (32)

Collapse
 
dog_smile_factory profile image
Dog Smile Factory

Learning PHP is a great choice, and I wouldn't be surprised if it's soon added to the list of technologies you love in your bio! For anyone interested, I would recommend PHP: The Right Way for solid advice on learning the language, as well as Laravel, a web application framework that makes coding with PHP a real pleasure. Best of luck with your exploration of PHP.

Collapse
 
mjcoder profile image
Mohammad Javed

Laravel +1

Collapse
 
lokidev profile image
LokiDev

Hey,

So I need to be the mean part here, I'm really sorry :/.

But there are a few "wrongs" in this article and I need to clarify

Syntax

While you CAN write ?> at the end of your files, you really SHOULDN'T. In Javascript there are multiple competing syntax-standards (like the one from AirBNB or the "Standard" standard.), but PHP is more like Python: There are PSR-2 and PSR-12 which describe exactly how standard-compliant code should look like. No more fights over indentation and so on ;).
php-fig.org/psr/psr-12/

Rules 2.2.:

The closing ?> tag MUST be omitted from files containing only PHP.

Emphasis on the "only".

Standards

Btw the next thing missing (maybe you didn't stumble upon it yet) are other references to the PSR. To step up your game, you really should try to understand all of them. But PLEASE refer from PSR-8, as it's the wrong time for now.

Declaring Variables

define doesn't really declare Variables, but compile time constants. They really can't be changed by any means and are like a little chipmunk replacing all the occurences with it's true value. This is the reason why you can't write sth. like:

define(POWERLEVEL, $sayajin->determinePowerlevel());
Enter fullscreen mode Exit fullscreen mode

What you CAN do is simple math:

define(POWERLEVEL, 2*9*500);
Enter fullscreen mode Exit fullscreen mode

Declaring Arrays

Not really about declaring arrays, but you say, that an Array is the only way to create a collection of key/value pairs without importing.
But you really can (and should) use data classes which hold your data and data collection. Like in javascript you can use them in parameters without their content to be copied by whole, but as a reference!

Functions

Nothing wrong here, but keep in mind, that all Objects are implicitly called by reference, while all scalars (int, string, arrays) are copied by value!

function applySomeProperty($someClass) {
    $someClass->bestBuddy = "Kuririn";
}

$unimportantClass = new class {};
applySomeProperty($unimportantClass);
echo $unimportantClass->newProperty; // Kuririn
Enter fullscreen mode Exit fullscreen mode

And while we're here: Since the 7.x Versions PHP supports types!

function someFunction(int $age, string $name): PersonObject {}
Enter fullscreen mode Exit fullscreen mode

You really should use them!

Classes

Not much here, but it's important to know, that you use :: in static context, while -> in private. Additionally there's a difference between $this::$varname and self::$varname.

Collapse
 
ziizium profile image
Habdul Hazeez

She said and I quote:

I'm still new to PHP

Collapse
 
lokidev profile image
LokiDev

So shes even more dependent on not learning sth. wrong.

How is someone supposed to learn and get better if everyone just sugar-coats you?

Thread Thread
 
ziizium profile image
Habdul Hazeez

So shes even more dependent on not learning sth. wrong.

How is someone supposed to learn and get better if everyone just sugar-coats you?

You might have missed the following comments and responses.

This comment:

Friendly reminder for a syntax shockingly difference between PHP and any other language. The dot ( . ) is the concatenation operator!

$hello = "hello";
$hello .= " world!";
echo $hello; // out: hello world!

For more info, check this out: positronx.io/php-concatenate-strin...

Her response:

I knew I was forgetting something, thank you!


Also this comment:

Setters are unnecessary in PHP. Use immutable private attributes and be happy.

Her response:

Thank you for the clarification!


And this:

Nice work Megan, just one thing: The spread operator is only available in PHP 7.4 everything else is awesome

And her response:

Thank you for the clarification! I'll add that in ASAP! 😀

Collapse
 
smoldev profile image
Megan Miller

I really appreciate this comment. Thank you so much! I'm still learning, so this is really helpful. 😊

Collapse
 
lokidev profile image
LokiDev

I really didn't want to be mean. I'm just the direct kind of guy. Another very helpful resource:
phptherightway.com/

This is a lot. Really. One chapter a week should be good enough to get you in the top 10% :).

Another tip: try to use tools like phpstan (or psalm) and php mess detector as early and strict as possible. They really force you to write better :)

Collapse
 
ziizium profile image
Habdul Hazeez

This brings back lots of memory from when I first learned PHP. Thank you.

When I find anyone who wants to know the similarities between JavaScript and PHP, I'll gladly point them to this post.

I'll bookmark it after hitting the submit button for this comment.

Collapse
 
upieez profile image
Samuel Huang

Awesome article! I started learning PHP awhile back and I always thought it has some similar style to JS. With you article, it confirmed my suspicion and learning about how classes work in PHP is so cool. Thank you for this :)

Collapse
 
smoldev profile image
Megan Miller

I'm so glad you enjoyed it!

Collapse
 
ansmtz profile image
ansmtz

PHP is awesome. Despite the rumours that it'll die soon.

Collapse
 
c0llinn profile image
Raphael Collin

Very nice article! You encouraged me to learn PHP.

Collapse
 
ziizium profile image
Habdul Hazeez

Can I make recommendations on resources to get you started?

Collapse
 
c0llinn profile image
Raphael Collin

Of course! Go ahead.

Thread Thread
 
ziizium profile image
Habdul Hazeez

Books

Website

Tools

Videos

*Security is important in Web application development and you should never consider it as an afterthought which is the main reason I included these resources.

Collapse
 
smoldev profile image
Megan Miller

I'm glad!

Collapse
 
dabretema profile image
Daniel Brétema

Friendly reminder for a syntax shockingly difference between PHP and any other language. The dot ( . ) is the concatenation operator!

$hello = "hello";
$hello .= " world!";
echo $hello; // out: hello world!

For more info, check this out: positronx.io/php-concatenate-strin...

Collapse
 
smoldev profile image
Megan Miller

I knew I was forgetting something, thank you!

Collapse
 
memitaru profile image
Ami Scott (they/them)

It's really cool seeing things laid out like this where I can compare them to JavaScript! Branching out into a new language always feels a little intimidating to me but seeing the JS and PHP side by side makes it a little less intimidating.

Collapse
 
smoldev profile image
Megan Miller

I'm glad you enjoyed it, that makes me so happy!

Collapse
 
vlasales profile image
Vlastimil Pospichal

Setters are unnecessary in PHP. Use immutable private attributes and be happy.

Collapse
 
smoldev profile image
Megan Miller

Thank you for the clarification!

Collapse
 
manuelojeda profile image
Manuel Ojeda

Nice work Megan, just one thing: The spread operator is only available in PHP 7.4 everything else is awesome

Collapse
 
smoldev profile image
Megan Miller

Thank you for the clarification! I'll add that in ASAP! 😀