A practical use case of anonymous classes in PHP
March 20, 2023 — Anonymous classes in PHP let you create a class on the fly without having to define a new class. They are especially useful when you want to create a class that is only used once.
A little memoize function in PHP
March 17, 2023 — So, Caleb Porzio recently shared a little memoize function in PHP. What the function does is pretty straightforward.
Two ways to merge arrays in PHP
January 26, 2023 — If you’re a seasoned PHP developer, you must have come across the need to merge two or more arrays in PHP. And the bona fide way to do this is by using the
Upgrade your PHP code to use PHP 8.2 features using Rector
January 10, 2023 — In this post, I’ll show you how to upgrade your PHP code to use PHP 8.2 features using Rector. I have written articles about how to upgrade to PHP 8 and PHP 8.1 previously.
Extract every array keys to variables of the same name in PHP
December 20, 2022 — There are times when you may want to extract every array keys to variables of the same name. For example, you have an array like so.
What's new in PHP 8.3 (Features and Improvements)
December 18, 2022 — PHP 8.3 is the next major release of the PHP programming language. It is scheduled to be released sometime in 2023.
PHP type declarations — A guide for beginners
December 4, 2022 — PHP 7 introduced a lot of new features to the language. One of them is the ability to declare the type of a function argument and the type of value that a function returns. This is called type declaration.
New features of PHP 8.2 in Code Blocks
November 27, 2022 — The release of PHP’s latest version, PHP 8.2, is just around the corner. On December 8, 2022 to be precise.
Ability to use Constants in Traits in PHP 8.2
November 18, 2022 — Constants are a great way to define values that are not going to change. They are also a great way to define values that are going to be used in multiple places.
The true type in PHP 8.2
October 18, 2022 — The latest and greatest version of PHP, PHP 8.2 is going to be released soon and it’s going to bring a lot of new features and improvements. In this post, I’ll talk about one of the new features in PHP 8.2 which is the
The new json_validate() function in PHP 8.3
October 9, 2022 — Today, if we want to validate a JSON string in PHP, we can use the
json_decode() function. Here’s how it works.
Converting PNG images to WebP using PHP
September 10, 2022 — Converting images from one format to another programmatically is sort of a common task. For example, you may want to convert all your PNG images to WebP format to save bandwidth and improve the performance of your application.
Running shell commands is dangerously simple in PHP
August 31, 2022 — PHP is one of those languages that are easy to learn and easy to use. But sometimes it surprises you with weird quirks that you would only imagine in your dreams.
A simple clamp() function in PHP
August 21, 2022 — If you have worked with CSS, you may have come across this function called clamp() that clamps a value between an upper and lower bound.
Check which Composer dependencies requires PHP 8 or 8.1
August 11, 2022 — Oftentimes, you may find it useful to check whether which among all the packages requires/depends upon a certain PHP version.
Retrieve the current PHP version as an integer
July 25, 2022 — Sometimes, when working on a feature that is tightly coupled with a certain version of the language, it’s important to check which version you’re running on your server.
Unpack arrays conditionally in PHP
May 16, 2022 — Array unpacking is a sleek way of assigning the value of array elements to variables in one shot like so.
Readonly classes in PHP 8.2
April 29, 2022 — When readonly properties were introduced in PHP 8.1, it has provided a legitimate way of making class properties truly “readonly”.
Null and false can be used as stand-alone types in PHP 8.2
April 24, 2022 — The latest version of PHP, PHP 8.1, has been around for quite some time and it comes packed with some great new features and enhancements.
Calculate age from the specified date in Carbon
April 15, 2022 — When you’re working with dates in Laravel, chances are high that you might have done it with this library called Carbon.
Refactoring conditionals to callables in PHP
March 16, 2022 — Recently, I came across a very handy tip by Nuno Maduro where you can refactor some of the conditionals in your code to callables to make your code more elegant and readable.
Safely convert any value to boolean in PHP
February 28, 2022 — Converting some values to boolean is a common task while building applications. Now, these values can be anything.
Fetch all the available time zones in PHP
February 16, 2022 — When you’re building a user-facing application, one of the most common scenarios is to let the user decide their respective time zone.
Human readable number formatting in PHP
February 10, 2022 — Numbers are tricky. Numbers are tricky because they have been used as a metric for a lot of things. Currency, scale, weather, science to name a few. And since numbers are associated with several different things, it’s important to represent them in a way humans can understand.
Intersection types in PHP 8.1
November 28, 2021 — When working with types in any language there is a couple of scenarios that can occur.
Quickly convert the PHP 8 codebase to use PHP 8.1 features
November 23, 2021 — The release of PHP’s latest version 8.1 is around the corner and there’s never a better time to upgrade your codebase to PHP’s latest and greated version yet!
First-class callables in PHP 8.1
October 14, 2021 — The newest release of PHP, v8.1, is around the corner and it will introduce a whole lot of new features, from the read only properties to the native enums. It’s pretty exciting!
How to get class instance without a constructor in PHP
September 13, 2021 — Have you ever stumbled upon a situation in which you need an instance of a class to create its object but with one condition and that is there is no constructor declared for that class?
Initialize objects right into the constructor parameters in PHP 8.1
September 11, 2021 — With the introduction of PHP 8, the language now allows us to declare the class properties right into the constructor parameters. This is called constructor property promotion.
A cool helper function to check if anything is blank in PHP
September 9, 2021 — There are a lot of different ways in PHP using which you can validate if the given value is “blank” or not. The method to validate depends upon the type of value that we’re targetting.
Checking if array keys are out of order using array_is_list() in PHP 8.1
July 8, 2021 — Working with arrays, there might come a time when you want to check if the array in question is a list or not. So, how does an array qualifies as a “list”?
Readonly properties are coming in PHP 8.1
July 7, 2021 — PHP, as a language, is ever-changing and ever-evolving. It’s not a language it was 10 years ago. This is all because the PHP’s core team which has been constantly improving minor things that might not look significant at first glance but when fixed/implemented, can dramatically improve the overall developer experience.
Numerical literal separator for better readability in PHP
June 18, 2021 — When you’re working with numbers in your code, they sometimes become hard to comprehend. For instance, in cases where numbers are too large in terms of length. Take the following for example.
Variable-length function arguments using spread token in PHP
May 12, 2021 — When working with functions, there might come the scenario where you’re unsure as to how many arguments a function would have. Basically, a function can have an unlimited number of arguments that you don’t define in the function signature.
Zipping up multiple arrays using array_map in PHP
April 17, 2021 — Little-known features are the best when you find them unknowingly. One such feature I came across recently is of the PHP’s popular array_map function.
How to get system timezone for macOS and Linux in PHP
March 17, 2021 — Oftentimes you would want to retrieve the user’s timezone to perform a certain task. And how would you retrieve it? One way to do it in PHP is by retrieving the timezone set on the user’s system.
Fibers or Coroutines for asynchronous programming in PHP 8.1
March 9, 2021 — There has been a scarcity of discussion in PHP land when it comes to asynchronous PHP. Maybe, PHP developers don’t seem to be interested in the very idea of it.
Limit the number of returned segments in PHP's explode()
February 10, 2021 — PHP’s documentation is a goldmine of little but helpful things which is when explored can help improve your code. But this kind of thing tends to get overlooked easily.
Native enumerations (enums) are coming in PHP 8.1
February 7, 2021 — Enums or enumerations or enumerator types are those little data structures that can be used to define a set of named values. More like constants. For instance, a contract status which can be “permanent”, “temp”, or “apprentice”. Or a order status that can be “ordered”, “dispatched”, “shipped” etc.
Array unpacking with string keys coming in PHP 8.1
January 28, 2021 — The spread operator in PHP is getting more awesome in PHP 8.1! So, to give you a primer, with the release of PHP 7.4, it got possible to merge multiple arrays by unpacking arrays into another array using the spread operator.
Method overloading in PHP
January 12, 2021 — Although the official PHP website’s documentation has a dedicated section on “Overloading”, it’s not truly called overloading by any means.
Get native type of a variable using get_debug_type() in PHP 8
January 3, 2021 — Before PHP 8, whenever you wanted to get the type of a variable, you could use the native gettype function. Check the examples below.
Using throw as an expression in PHP 8
December 23, 2020 — Up until now, when you want to throw exceptions from your code, you would use the
throw keyword to throw the exception which can be caught by the
catch block like so.
Crawl external websites and perform actions using Symfony's BrowserKit
December 21, 2020 — There might be some situations where you would want to crawl a third-party website and perform some actions right from your PHP codebase. For instance, submitting forms, logging into your account, clicking links, etc. to add some degree of automation in your workflow.
The get_class() alternative in PHP 8
December 5, 2020 — If you’re working with PHP for a while, there might be a good chance that you’d be in need to fetch the class of an object. This could be mostly for debugging purposes.
Exciting new features and improvements in PHP 8
November 23, 2020 — As the official release date (26th November 2020) of PHP’s latest and greatest version PHP 8 is approaching, let’s take a look at every new feature and improvement that the PHP team has managed to fit in this version.
Using .htaccess to access environment variables in PHP
November 3, 2020 — If you’re working with the latest frameworks, it’s not very difficult to set up environment variables for your app.
How to upgrade legacy codebase to use PHP 8.0 features using Rector
November 1, 2020 — The newest version of PHP, the PHP 8.0, is coming later this year (November 26, 2020) and it will come packed with many new features such as constructor property promotion, match expressions, nullsafe operator, attributes and a lot others.
How to use Attributes and their real-world usage in PHP 8.0
October 30, 2020 — Of many great new features that PHP 8 has introduced, one of the most confusing that I found were called “Attributes”, until today. Attributes in PHP 8 got revised many times before gets settled to the current implementation that we will see in a bit.
Composer 2.0 — How to upgrade and features overview
October 26, 2020 — I’ve said it earlier and I’m saying it today as well that Composer is the backbone of modern development in the PHP landscape. It has been so much easier to pull in open-source packages into your projects which weren’t possible in the pre-Composer era.
Convert HTML to PDF like a pro using DocRaptor API (Sponsor)
October 16, 2020 — If you’ve ever worked on enterprise-level web applications, there’s a good chance that you would have in need to convert documents from one format to another such as converting an HTML document to PDF.
Short functions could be coming in PHP 8.1
September 28, 2020 — PHP 8 is around the corner and it is coming packed with a lot of new features. But there’s something exciting cooking in PHP 8.1 already.
Import and export only a function under namespace in PHP
September 22, 2020 — The standard way of including files in modern PHP development is using namespaces and autoloading of classes using Composer.
Prevent spammy form submissions by bots using this Honeypot technique in PHP
September 17, 2020 — In modern web applications, one of the pain points everyone faces at some point is spam submissions to forms by automated bots.
Expose your local websites to the internet using this open source tool in PHP
August 12, 2020 — Recently, I’ve been working on a Laravel app and one of my friends wanted to see it in action who’s sitting seven ocean apart. But, I didn’t have an actual server to host it and to make it accessible for my friend. And so, I was looking for a tool/API which can expose my local website instance to the internet.
Accessing private methods and properties outside of class using reflection in PHP
August 11, 2020 — In PHP, the visibility of a property, a method, or a constant can be defined by prefixing the declaration using keywords
private. Here is how these modifiers work.
Proposed named arguments in PHP 8
July 10, 2020 — Update: Named parameters have been accepted to be included in PHP 8. A 2/3 majority in voting from members was required and it got the required votes! Here’s the RFC that got accepted.
Match expression - An alternative to switch statement in PHP 8
July 3, 2020 — The switch statement in PHP is great when you want check condition on the same expression without incorporating many
if statements altogether.
The mixed type of PHP 8
June 22, 2020 — Up until now, or precisely before PHP 8, whenever you were unsure about which type to use for the propperty or return type, you’d leave it without assigning any type. And if you’re using an IDE such as PhpStorm, the docBlock would mark those properties as
mixed type like so.
Refactor conditions to a method for better readability in PHP
June 16, 2020 — Refactoring is important in programming things. It is a process of restructuring existing computer code—changing the factoring—without changing its external behavior. It makes code more readable, structured and easy to process.
These new string functions are coming in PHP 8
June 13, 2020 — Who would’ve thought that PHP would have to wait till its version 8 or rather 25 years after its inception, to get a truly native and understandable function to check if a string is contained in another string?!
Non-capturing exception catches in PHP 8
June 10, 2020 — The usual way of handling the exception is by requiring the
catch block to catch the exception (thrown from the
try block) to a variable like so.
Constructor Property Promotion in PHP 8
June 9, 2020 — Wouldn’t it be nice if you don’t have to declare the class property over and over again just to use it across the class? Currently, you’d do it by first declaring it…
This nullsafe operator could come in PHP 8
June 4, 2020 — Have you ever wanted a feature where you would only want to call a method or fetch a property on the result of an expression if it is not
null? So, for instance, check the following code.
Strict typing vs. Weak typing in PHP
June 1, 2020 — With PHP 5, the core team had introduced type declarations (also known as type-hinting) that allow functions to require that parameters are of a certain type at call time. If the given value is of the incorrect type, then an error is generated: in PHP 5, this will be a recoverable fatal error, while PHP 7 will throw a TypeError exception.
Unpacking inside arrays using spread operator in PHP
Using ::class static class keyword in PHP
May 8, 2020 — If you’ve worked with modern frameworks such as Laravel, you might have seen this keyword
::class be used extensively throughout the application.
Null coalescing assignment operator in PHP
May 4, 2020 — When PHP 7.0 released, it has added many nice things in PHP’s toolbelt of utilities. One of the things among this was Null coalescing assignment operator (??).
How to implement wrapper classes in PHP
May 4, 2020 — If you look at PHP’s core helper functions, they aren’t very intuitive to use and are pretty inconsistent at times. For instance, the array_map function is used to apply the callback to the elements of the given arrays. Here’s how its definition looks like.
Post data using streams in PHP
April 17, 2020 — I recently stumbled upon this ghost feature of PHP using which you can actually use streams in order to post data using a HTTP POST request.
Immediately Invoked Function Expression in PHP
April 15, 2020 — Sometimes all you need is to define and call function at the same time and only once throughout the scope. Such functions are called as Immediately Invoke Function Expression (IIFE) also known as Self-Executing Anonymous Function.
Benefits of using custom exceptions in PHP
April 1, 2020 — Exceptions are really useful when you want to handle some situations which can not be handled gracefully otherwise. So, using exceptions, you can handle certain sceanrios by showing a nice error message. Take the following example for instance.
Using arrow functions in PHP 7.4
Constructor property promotion could be coming to PHP
March 27, 2020 — Have you ever felt the class properties that you’re using in the constructor are essentially repeated multiple times? i.e At the declaration, in the constructor parameters and while doing assignment in the constructor. For instance, take the following example.
Computed properties and methods in PHP
Multiple constructors in PHP
March 2, 2020 — Constructors are a really important part of the class-based object oriented programming. Through constuctors, a newly created objects initialize properties automatically before it is usable. In PHP, a constructor is a method named
__construct(), which the keyword
new automatically calls after creating the object. Constructors can also accept arguments, in which case, when the
new statement is written, you also need to send the constructor arguments for the parameters.
Remembering what spaceship operator do on comparison in PHP
February 20, 2020 — PHP has introduced an operator called “spaceship opearator” (
<=>) with the release of PHP7. What this spaceship operator do is compare two expressions i.e. its two operands, let’s say
$b, and returns -1, 0 or 1 when
$a is respectively less than, equal to, or greater than
Using register_shutdown_function() instead of desctructor in PHP
February 18, 2020 — The usual and might be the most used way of cleaning the object is to use the good old __destruct() magic method in PHP. The magic method proves to be good in most of the cases. But there might be some scenario where even the
__destruct() method will fail. For instance, a scenario where your PHP script exceeds the maximum execution time, and terminates thusly. And a fatal error would occur called
Maximum execution time of 20 seconds exceeded in - on line XX.
Some lesser known facts of Traits in PHP
February 10, 2020 — Traits in PHP is a way of re-using the code. Basically, Traits are assistive copy-paste mechanism provided by the language itself. Using Traits, developers can reduce the limitations of single inheritence based languages such as PHP. I have written a dedicated article about it if you want to check it out.
When to use finally in exception handling in PHP
January 31, 2020 — Exception handling is an essential part of the software development workflow. It is used to handle the runtime errors so that the normal flow of the application can be maintained.
Little trick to loop through class properties in PHP
January 26, 2020 — There’s this little trick in PHP that I got to know about today. The trick basically is, you can loop through all the class properties having the “public” visibility just by iterating over the class object using loop construct such as
Verify if email is from a valid domain in PHP
January 24, 2020 — Working on an application which received user signups and let’s suppose it’s built on top of PHP, you want to validate that the email the user enters is valid. Sure, you’ll check that the email entered is a “syntactically” valid one by using one of these methods.
Using objects as arrays (with a real world example) in PHP
January 15, 2020 — Sometimes, it’s convenient when you could get to access class objects as arrays. For instance, the time when one of the class properties is of type array and you want to manipulate it just like you’d do with an array without exposing it during object creation. I’ve included a real world example of where this could be useful, at the end of the article. So, read on!
Premature optimization is dangerous
December 18, 2019 — Working with PHP, it would be pretty obvious you’d be worried about the performance of your application. And because of this anxiety, you start to optimize trivial things such as replacing double quotes(“) to single quotes(‘), use
echo instead of
print_r, or using static methods in order to gain those little performance gains during the initial few days of your application development itself. Optimizing these thigs is good and all.
Method chaining in PHP in a nutshell
December 16, 2019 — In this short article, I’m going to explain what method chaining is and how it can prove to be useful as an object oriented design pattern.
Top features of PHP 7.4 Explained!
December 7, 2019 — PHP 7.4 is finally released a few days ago. It’s a fourth feature update to the PHP 7 series and it comes with a very interesting set of features which I’m going to talk about in this article. Some of are very long overdue such as unpacking arrays, typed properties and so forth. However, these all comes with some sort of caveats. Let’s talk about all of the new features in details.
My favorite PhpStorm tricks and tips that I use daily
December 5, 2019 — Jetbrain’s PhpStorm is my goto IDE when it comes to the PHP developement. Be it Laravel, Symphony or Magento. It’s like a gold standard. The kind of intelligent features it offers is unmatchable and almost irrplaceable by any IDE of this level.
Dependency Injection vs. Dependency Injection Container in PHP
November 26, 2019 — In this article, I'll talk about Dependency Injection and Dependency Injection Container and why one should use DI Containers.
Nullable types in PHP 7.1
November 20, 2019 — In this article, I've discussed regarding Nullable types that are introduced in PHP 7.1 and its usefulness.
The most easiest and clean way to unset a cookie in PHP
November 12, 2019 — Today, I got to know about a very clean looking and intuitive way of unsetting/deleting a cookie from client's browser using PHP. No "setting the expiry time in past" bullshit.
Union types are coming in PHP 8
October 30, 2019 — In this article, I’m going to discuss about the union types which are going to come in future versions of PHP through this RFC. To understand why and how are union types important in PHP, let’s first understand what are union types.
The difference between 'elseif' and 'else if' in PHP
September 29, 2019 — PHP is funny sometimes. There are many things in PHP which behaves differently instead of the way you think might work. I recently stumbled upon one such thing while working on one of my projects.
Built-in password hashing and verification in PHP
September 2, 2019 — Passwords are an integral part of today’s authentication based web applications. In fact, Passwords have been used since ancient times. Sentries would challenge those wishing to enter an area to supply a password or watchword, and would only allow a person or group to pass if they knew the password. In modern web application passwords are used in combination with usernames to authenticate users. So, basically, we’d need to fields in order to store username and password for each user both of which are supplied by user at the time of signing up to the web application.
Reasons to use Composition over Inheritance in PHP
August 22, 2019 — In object-oriented programming, there are two ways using which classes can achieve polymorphic behavior: “Inheritance” & “Composition”.
Better error handling in core PHP functions using Safe PHP
August 13, 2019 — Some of the PHP’s core functions are designed in such a way that they do not handle exceptions in a better way. Instead, they just return
false if there’s any error. This makes developers to handle those error themselves. Take the example below.
Late static binding in PHP - What, How & When
August 7, 2019 — The inheritence tree in PHP quickly gets dirty if you’re using mix of
non-static methods into your classes and the inheritence is deeply nested. Take from example here.
A deep dive into Generators in PHP
July 31, 2019 — Have you ever stuck in a situation where the code that you’ve wrote uses foreach to iterate over a set of data into an array and which ultimately caused you to exceed a memory? Well, I’ve been to. Many times.
Get grandparent instance of certain class in PHP
July 25, 2019 — Recently, I stumbled upon a scenario where I had to extend a class. I'm going to explain what issue I had faced and what's the role of using the grandparent instance of the class to overcome that issue in this article.
A closer look at Invokable classes in PHP
June 10, 2019 — In PHP, Invokables refer to any class that may be instantiated without any constructor arguments. In other words, one should be able to create an instance solely be calling
new $className(). To implement an invokable class, one needs to use __invoke() magic method of PHP. Before we understand how invokable exactly works, let’s take a look why invokable classes even exists in PHP.
PHP 7.4 will support first-class property type declarations
May 2, 2019 — With the introduction of scalar type declaration and return type declaration in PHP 7.0, the language’s type system got improved at some extent. Although it’s great to have some layer of strictness, it’s still missing the support to declare typed properties. But from PHP 7.4, it seems, it’s going to change because according to this accepted RFC, PHP 7.4 will be getting support for first-class property type declarations.
Get all admin users as an array in Magento 2
February 22, 2019 — Today, while working with a project which happens to be bulit on top of Magento 2, I needed to find a way to get the list all the admin users as an array.
Packages to make your Laravel development experience awesome.
February 9, 2019 — While developing applications(not necessarily with Laravel), you come across the situation where you need to implement certain functionality. In such cases you shouldn’t want to reinvent the wheel if the functionality is been implemented by someone as a package, accepted well by the community and is ready to be consumed. It’s a no-brainer. I use to follow the same approach and today in this article, I’m going to list out some of my favorite Laravel packages which have made my experience with development in Laravel delicious.
This is why PHP don't have multiple inheritance
January 17, 2019 — PHP has evolved greatly as a language over the years. From a simple functional scripting language which initially started by Rasmus Lerdorf as his hobby project to supporting object oriented programming features PHP has come a long way. Although, PHP has been implementing and improving features of object oriented programming in its every release, there is this one feature which is missing and I’ve always wondered why it is not there in PHP all these years. Yes, I’m talking about multiple inheritance.
Build your own Laravel artisan commands for your project
January 9, 2019 — When working on a project, there comes a time when you need to automate certain tasks. In such cases, it is better to use a CLI tool which can be run from the command prompt because using a web APIs for certain tasks is cumbersome.
Why you should use Laravel Queues
December 21, 2018 — There comes times when you wouldn’t want your end users staring at white screens or that intimidating loaders for a long time. For instance when user registers to your site, you must have configured your website to send a welcome email or a confirmation email upon registering. So, that operation should be snappy and for that purpose you’d actually want to reduce the amount of time your app takes while sending the email to the user. Laravel Queues comes to the recue for achieving such kind of time consuming tasks.
Top fetaures of PHP 7.3
December 8, 2018 — PHP development team has just released PHP 7.3 with general availability. This release brings general improvements along with some new features. Even though this is a stable release, the team hasn’t provided concrete migration guide if you want to migrate from the older PHP versions. Maybe they will release those on a later date.
Array destructuring in PHP
Using private repositories as a composer package in PHP
September 5, 2018 — Composer is the goto method of adding dependencies in modern PHP application. You search for a library for a concerned functionality and you’ll probably find the one in the large database of the Pacakgist. But there comes a time where you’d want to use a library which is private and should be only available to you. Well, the good news is, you can achieve this using this trick.
Laravel - Accessors & Mutators
August 23, 2017 — Accessors and mutators allow you to format Eloquent attribute values when you retrieve or set them on model instances. I’ll explain how you can you use them into your app.
Laravel Eager Loading - load() Vs. with()
August 17, 2017 — Today, while working with one of my projects(which is built on top Laravel) I bumped into the situation where I needed to get associated model’s data for one of the models. So here, I had two approaches in Laravel to accomplish this which are basically called Eager Loading: