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.

self:: vs static:: in PHP

0 👍
👎 1
 PHP
 LAMP

self:: vs static:: in PHP is all about inheritance and late static binding.  It’s used when you are dealing with overrides and methods coming from the parent class.

 

self::

 - Refers to the class where the method is defined.

 - Does not consider inheritance overrides.

static::

 - Refers to the class that is actually called at runtime.

 - This is called late static binding.
- Allows child classes to override static properties/methods and still be respected.

 

 class Automobile {

    public static $type = "Automobile";

 

    public static function getTypeUsingSelf() {

        return self::$type// bound to Automobile

    }

 

    public static function getTypeUsingStatic() {

        return static::$type; // late static binding

    }

 }

 

 class Car extends Automobile {

    public static $type = "Car";

 }

 

 class Truck extends Automobile {

    public static $type = "Truck";

 }

 

 class Van extends Automobile {

    public static $type = "Van";

 }

 

 // ------------------- USAGE -------------------

 

 echo Car::getTypeUsingSelf();   // Output: Automobile

 echo "<br>";

 echo Car::getTypeUsingStatic(); // Output: Car

 

 

Using the Javascript Switch Statement

1 👍
👎 0
 NodeJS
 ReactJS
 Javascript

Overview of the Switch Statement


  The switch statement is a control structure available in almost every programming and scripting language.  It allows the developer to execute different blocks of code based on the value of an expression.  It is often used as a cleaner alternative to multiple if-else statements.  You may be asking yourself why use the switch statement since we already have if-else.  


   There are differences though.  And depending on the task-at-hand, the switch statement can be a better alternative than
if-else.  

Structure:

 

 switch (expression) {

    case value1:

        // execute this code block only

        break;

    case value2:

        // execute this code block only

        break;

    default:

        // execute if no cases match

 }


   A
switch statement evaluates an expression and executes the code block for the first case that matches its value.

   The break keyword is crucial. When encountered, it exits the entire switch statement immediately. Without it, execution will "fall through" and run the code in the subsequent case, even if the value doesn't match.  If no matching case is found, the optional default block is executed.

Example:

 

 let day = 'Monday';

 let output = '';

 switch (day) {

    case 'Monday':

        output = `Day is Monday`;

    case 'Tuesday':

        output = `Day is Tuesday`;

        break;

    case 'Wednesday':

        output = `Day is Wednesday`;

        break;

    case 'Thursday':

        output = `Day is Thursday`;

        break;

    case 'Friday':

        output = `Day is Friday`;

        break;

    case 'Saturday':

        output = `Day is Saturday`;

        break;

    case 'Sunday':

        output = `Day is Sunday`;

        break;

    default:

        output = `No day specified`;

 }

 

 // Output if day == 'Monday' OR day == 'Tuesday':

 // Day is Tuesday

 

 // Output if day == 'Saturday':

 // Day is Saturday

 

 // Output if day == 'Nothing'

 // No day specified

 


   This example demonstrates a crucial concept in JavaScript's
switch statement: fallthrough.  When day is 'Monday', the output will indeed be "Day is Tuesday".  Here’s why: The switch statement finds a match on case 'Monday' and begins executing the code on the next line, setting output = 'Day is Monday'.

  Because there is no break keyword at the end of the 'Monday' case, the logic "falls through" and continues to execute the very next line of code, which is the start of the 'Tuesday' case.  It then executes output = 'Day is Tuesday', overwriting the previous value.  Finally, the break keyword at the end of the 'Tuesday' case is encountered, which halts the execution of the switch block entirely.

   The break statement is not optional for most use cases. It is essential for exiting the switch block once a specific case's code has finished running. Without it, execution will continue into the next case, whether it matches or not.


   The
default case is only executed if no other case values match the expression. It will not be executed simply because of a fallthrough from a matched case (unless that fallthrough leads all the way to it).

PHP Object __invoke()

0 👍
👎 0
 PHP

What is the __invoke() method used for in objects?  The __invoke() method is a PHP magic method that allows an object to be called as if it were a function.  It’s great for maintaining state and focusing on a single calculation.

Let’s take a look a more practical use.  In this example we will use it for issuing API requests:

 

 class HttpRequest {

   

    public function __construct(private string $url)

    {   

    }

 

    public function __invoke($data) {

        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, $this->url);

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        $response = curl_exec($ch);

        curl_close($ch);

        return $response;

    }

 }

 

 $amazon = new HttpRequest('https://api.example.com/amazon/store');

 $temu = new HttpRequest('https://api.example.com/temu/store');

 

 $amazonResponse = $amazon(['item_id'=>12333]);

 $temuResponse = $amazon(['item_id'=>12333]);

 

 

How to Backup and Restore with pg_dump and mysqldump

0 👍
👎 0
 Database
 PostgreSQL
 MySQL

This tutorial guides you through backing up MySQL and PostgreSQL databases from the command line. While their native tools—mysqldump and pg_dump—share a similar purpose, their command syntax differs. We will cover the essential commands for both systems, highlighting their key similarities and differences. 

Backup MySQL / MariaDB Database

 

Export every table’s schema and existing records to an SQL executable script.


mysqldump -u username -p database_name > database.sql

 

This will export the specified table’s schema and records to an executable script.

 

 mysqldump -u username -p database_name table_name > db_table.sql

 

 

This will export the specified table’s data only(no schema).

 
mysqldump -u username -p --no-create-info database_name table_name > table_data.sql

 

 

This will export the specified table’s schema only(no data).


mysqldump -u username -p --no-data database_name table_name > table_schema.sql

 

Restore MySQL / MariaDB Database

 

 mysql -u username -p database_name < database.sql

 

 

Backup PostgreSQL Database

 

Export every table’s schema and existing records to an SQL executable script.

 

 pg_dump -U username database_name > database.sql

 

 

This will export both the specified table’s schema and data to an executable script.

 

 pg_dump -U username -t table_name database_name > table.sql

 

 

Only data (no schema):

 

 pg_dump -U username -a -t table_name database_name > table_data.sql

 

 

Only schema (no data):

 

 pg_dump -U username -s -t table_name database_name > table_schema.sql


Restore PostgreSQL Database

 

 psql -U username -d database_name -f database.sql

 




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];

 

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