Web Development Articles

A Quick HowTo of PHP Operators

0 👍
👎 0
 LAMP

Math Operators

Addition:
Caculate the sum of two numbers using the + operator.

$sum = 1 + 3;
The value of $sum is 4.

Subtraction:
Caculate the difference of two numbers using the - operator.

$diff = 3 - 2;
The value of $diff is 1.

Division:
Calculate the quotient of two numbers using the / operator.

$quotient = 4 / 2;
The value of $quotient is 2.

Multiplication:
Calculate the product using the * operator.

$product = 4 * 5;
The value of $product is 20.

Modulo:
Gives the remainder after dividing two numbers the % operator.

$remainder = 10 % 3;
The value of $remainder is 1.

PHP Object Oriented Class Inheritance

0 👍
👎 0
 PHP
 LAMP

PHP class inheritance is a mechanism that allows one class (called the child class or subclass) to inherit properties and methods from another class (called the parent class or superclass).

 

This allows you to reuse code, extend existing functionality, and follow the principle of "Don’t Repeat Yourself (DRY)".


Basics of Inheritance

1. The extends keyword is used in PHP to create inheritance.

2. A child class automatically inherits all the public and protected properties and methods of its parent class.

3. The child class can:

       A. Use the inherited methods and properties directly.

       B. Override methods from the parent class.

       C. Add new methods and properties.

 

Example 1: Basic Inheritance

Here, the Dog class inherits from the Animal class but overrides the speak() method.

 

 // Parent class

 class Animal {

    public $name;

 

    public function __construct($name) {

        $this->name = $name;

    }

 

    public function speak() {

        echo "$this->name makes a sound.<br>";

    }

 }

 

 // Child class

 class Dog extends Animal {

    public function speak() {

        echo "$this->name barks! Woof Woof!<br>";

    }

 }

 

 // Usage

 $animal = new Animal("Generic Animal");

 $animal->speak(); // Output: Generic Animal makes a sound.

 

 $dog = new Dog("Buddy");

 $dog->speak(); // Output: Buddy barks! Woof Woof!

 

 

Example 2: Using parent:: to Call Parent Methods

The Car class overrides the start() method but still uses the parent’s method with parent::start().

 

 class Vehicle {

    public function start() {

        echo "Starting the vehicle...<br>";

    }

 }

 

 class Car extends Vehicle {

    public function start() {

        // Call the parent method first

        parent::start();

        echo "Car engine started!<br>";

    }

 }

 

 $car = new Car();

 $car->start();

 // Output:

 // Starting the vehicle...

 // Car engine started!

 

 

Example 3: Multilevel Inheritance

Human inherits from Animal, and Animal inherits from LivingBeing. So, Human has all methods from both parents.

 

 class LivingBeing {

    public function breathe() {

        echo "Breathing...<br>";

    }

 }

 

 class Animal extends LivingBeing {

    public function eat() {

        echo "Eating...<br>";

    }

 }

 

 class Human extends Animal {

    public function speak() {

        echo "Speaking...<br>";

    }

 }

 

 $person = new Human();

 $person->breathe(); // From LivingBeing

 $person->eat();     // From Animal

 $person->speak();   // From Human

 

 

JavaScript Variable Types (var, const, let)

0 👍
👎 0
 MySQL

There are 3 types of variables commonly used in javascript.  The main difference with the let type it's block scope.  If it's defined inside of a block it can't be accessed outside of the block.   Let's look at each in more detail:

const

Variables defined with const cannot be Redeclared
Variables defined with const cannot be Reassigned
Variables defined with const have Block Scope


// INCORRECT - must be assigned a value when it's declared.
const x;  
x = 1.999;

// INCORRECT - it cannot be reassigned a value
const x = 1.999;

x = 8;  

// IF defined inside of a block it has block scope. Look at example below:
if( somecondition )
{
   const x = 9;
}
// x cannot be access here outside of the "block", curly brackets.
// Below are valid usage of const:
// Example 1:
if( condition )
{
   const x = 8;
   console.log(x);
}

// Example 2:
const x = 8;
if( condition )
{
   console.log(x);
}


PHP Null Coalescing Nesting AND Chaining

0 👍
👎 0
 Laravel
 PHP

PHP Null Coalescing Nesting AND Chaining

The null coalescing operator is essential for writing clean, safe PHP code that gracefully handles missing data without generating warnings or errors.

 

Null Coalescing Assignment Operator (??)

 

 // ternary operator usage

 $value = isset($a) ? $a : (isset($b) ? $b : $c);

 

 // null-coalescing shorthand for above solution

 $value = $a ?? $b ?? $c;



Null Coalescing Assignment Operator (??=)

 

 // Only assign if variable is null or doesn't exist

 $array['key'] ??= 'default value';

 $user->name ??= 'Anonymous';

 

 // Equivalent to:

 if (!isset($array['key'])) {

    $array['key'] = 'default value';

 }

 

 

Use with error suppression

 

 $value = $object->property->nestedProperty ?: 'default';

 echo "Value: ".$value."\r\n"; //Warning is thrown

 

 

 $value = @$object->property->nestedProperty ?? 'default';

 echo "Value: ".$value."\r\n"; // Value: default 

 

 

Javascript Spread Operator ...

0 👍
👎 0
 MongoDB

The javascript spread operator ... is a convenient way to insert an array into a second array.  Used mainly when defining the array data.  Consider the following:

/****
 * The x array is placed inside of noSpread as a child array inside.
 * noSpread array is now ['u', Array(2), 3, 7]
 ****/
let x = ['a', 2];
let noSpread = ['u', x, 3, 7];

/***
 * using the spread operator ...x
 * the spread array is now ['u', 'a', 2, 5, 6]
 ***/
 
let x = ['a', 2];
let spread = ['u', ...x, 5, 6];

 

Defining a Javascript Function

0 👍
👎 0
 NodeJS
 Javascript

How To Define a JavaScript Function

There are a few different ways to declare a function in Javascript applications. I’ve laid out 4 ways below so choose the method that best fits your use case! Function declarations are great for named functions, whereas arrow functions are excellent for callbacks and shorter functions.  

Using Function Declaration

 

 /** Function Declaration */

 function functionName(parameters) {

    // code to be executed

    return value;

 }

 

 // Example

 function greet(name) {

    return "Hello, " + name + "!";

 }

 console.log(`My name is ${greet("Alice")}`); // "Hello, Alice!"

 

 

Using Function Expression

 

 /** Function Expression */

 const functionName = function(parameters) {

    // code to be executed

    return value;

 };

 

 // Example

 const multiply = function(a, b) {

    return a * b;

 };

 console.log(`5 * 3 = ${multiply(5, 3)}`); // 15

 

 

Using Arrow Functions (ES6)

 

 /** Arrow Function (ES6) */

 const functionName = (parameters) => {

    // code to be executed

    return value;

 };

 

 // Examples with different syntax

 const square = (x) => {

    return x * x;

 };

 console.log(`Square of 4: ${square(4)}`); // 16

 

 // Implicit return (for single expressions)

 const squareRoot = x => x ** 0.5;

 console.log(`Square Root of 8: ${squareRoot(8)}`);

 

 // Multiple parameters

 const add = (a, b) => a + b;

 console.log(`2 + 3 = ${add(2, 3)}`); // 5

 

 // No parameters

 const title = () => "Math";

 console.log(`The page title is "${pageTitle()}"`);

 

 

Using the Function Constructor

 

 /** 4. Function Constructor (less common) */

 const functionName = new Function("parameters", "function body");

 

 // Example

 const divide = new Function("a", "b", "return a / b;");

 console.log(divide(10, 2)); // 5

 



Master JavaScript Asynchronous Programming with Promise.allSettled()

0 👍
👎 0
 Javascript

The Promise.allSettled() method is a powerful tool for handling multiple promises in JavaScript. It returns a single Promise that resolves with an array of objects, each representing the outcome of a promise in the input array.

Each outcome object contains a status property, which is either 'fulfilled' or 'rejected'.

- If the status is 'fulfilled', the object will also contain a value property with the resolved value.

- If the status is 'rejected', the object will contain a reason property with the error (typically the value passed to reject).

Key Difference: Promise.allSettled() vs. Promise.all()

Unlike Promise.all(), which immediately rejects if any promise in the iterable is rejected, Promise.allSettled() never short-circuits. It waits for all promises to settle (either fulfill or reject), making it ideal for use cases where you need to know the result of every asynchronous operation, regardless of individual failures. This provides a more robust way for error handling in async/await and promise chains.

When to use Promise.allSettled() in JavaScript?
Use it whenever you need to process the results of multiple independent asynchronous operations and you don't want a single failure to prevent you from handling the others. Common scenarios include making multiple API calls or database queries where individual failures are non-critical.

The following example demonstrates how to use Promise.allSettled() to handle a mix of successful and failed promises.

 

 // Example: Handling multiple API calls or asynchronous tasks

 const p1 = new Promise((resolve, reject) => {

    setTimeout(resolve, 200, "Data for User 1"); // Simulates a successful API call

 });

 const p2 = new Promise((resolve, reject) => {

    setTimeout(resolve, 200, "Data for User 2"); // Simulates another successful call

 });

 const p3 = new Promise((resolve, reject) => {

    setTimeout(reject, 200, "User 3 not found"); // Simulates a failed API call (e.g., 404)

 });

 const p4 = new Promise((resolve, reject) => {

    setTimeout(reject, 200, "Server error for User 4"); // Simulates a server error (e.g., 500)

 });

 

 // Execute all promises and handle results with allSettled

 Promise.allSettled([p1, p2, p3, p4])

 .then(results => {

    console.log("All operations settled:");

    results.forEach((result, index) => {

       if (result.status === 'fulfilled') {

           console.log(`Promise ${index + 1}: Success -`, result.value);

       } else {

           console.log(`Promise ${index + 1}: Failed -`, result.reason);

       }

    });

 });

 

 //             ** CONSOLE OUTPUT **

 // All operations settled:

 // Promise 1: Success - Data for User 1

 // Promise 2: Success - Data for User 2

 // Promise 3: Failed - User 3 not found

 // Promise 4: Failed - Server error for User 4