miércoles, 18 de febrero de 2026

named functions an default arguments and null handling

<?php


  function Test(?string $name=null, ?int $age=null){

    

    $name= $name??"Guest";

    

    $age=$age??0;

    

    

    echo "Hello my name is $name my age is $age \n";

  }

    Test(age:44, name:"Ambiorix");

    


  ?>

Output:

9 ms | 18.4 MB
Hello my name is Ambiorix my age is 44 

martes, 17 de febrero de 2026

Oop Guide practice

<?php


class Human{


// Class variables


public static int $globalID = 1000;



//Instance variables


   private  string $name;

   

private int $instanceNumId;


  //Constructor initializer

  

  

  public function __construct(string $name){


$this->intanceNumId=self::$globalID+=1;


$this->name=$name;



  }


  

//Getter methods

  function getId(){


  

    return $this->intanceNumId;


  }

  function getName(){


    return $this->name;


  }


}


//Class instances

$Test0 =  new Human("Class 0");


$Test1 =  new Human("Class 1");


echo  "--- Instance ID  {$Test0->getId()}\n";


echo  "--- Instance ID  {$Test1->getId()}\n";


//Accessing class static fields


echo  " Global  class ID ".Human::$globalID." , instance name {$Test0->getName()}  \n";


?>


sábado, 20 de diciembre de 2025

try catch finally

<?php


function rankUser($age) {

    $rank = null;

    $status = null;


    try {

        if ($age >= 18 && $age <= 65) {

            $status = "allowed";


            if ($age < 45) {

                $rank = "Rookie";

            } else {

                $rank = "Veteran";

            }


        } else {

            $status = "denied";

            throw new Exception("Age must be between 18 and 65\n");

        }


    } catch (Exception $e) {

        echo 'Caught exception: ' . $e->getMessage() . "\n";

    } finally {

        if ($rank) {

            echo "User status $status, and Rank $rank";

        } else {

            echo "Sorry, your status is $status. You don't meet age requirements.";

        }

    }

}


rankUser(13);


?>


viernes, 12 de diciembre de 2025

Global variables insdide and outside a function

 <?php

$somevar = 15;

function addit() {

 GLOBAL $somevar;

 $somevar++;

 print "Somevar is $somevar";

}

addit();


?>



<?php

$somevar = 15;

function addit() {

 $GLOBALS["somevar"]++;

}

addit();

print "Somevar is ".$somevar;


?>

Static variables

 <?php

function keep_track() {

 STATIC $count = 0;

 $count++;

 print $count;

 print "<br>";

}

keep_track();

keep_track();

keep_track();

?>

Error reporting

<?php

// -------------------------------

// PHP Error Reporting Example

// -------------------------------


// Report all errors except user warnings and notices

error_reporting(E_ALL & ~E_USER_WARNING & ~E_USER_NOTICE);


// Display errors on screen (for development)

ini_set('display_errors', 1);


// Add a prefix to each error message

ini_set('error_prepend_string', '<strong>Error:</strong> ');


// Example errors

echo $undefined_variable;                 // Notice (ignored)

trigger_error("This is a warning", E_USER_WARNING);  // User warning (ignored)

trigger_error("This is an error", E_USER_ERROR);     // User error (shown with prefix)

?>

jueves, 4 de diciembre de 2025

 $options = array(

    CURLOPT_URL => 'http://www.example.com/',

    CURLOPT_RETURNTRANSFER => true,  // boolean

    CURLOPT_HEADER => false,         // boolean

    CURLOPT_USERAGENT => ''          // empty string, will be filtered

);


// Filter only non-empty strings

$options = array_filter($options, fn($v) => gettype($v) === 'string' && strlen($v) > 0);


$ch = curl_init();

foreach($options as $opt => $val){

    curl_setopt($ch, $opt, $val);

}


$response = curl_exec($ch);

curl_close($ch);


curl

<?php
// Create a curl handle to a non-existing location
$ch = curl_init('http://404.php.net/');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
if(curl_exec($ch) === false)
{
echo
'Curl error: ' . curl_error($ch);
}
else
{
echo
'Operation completed without any errors';

}


//echo $error =( curl_errno($ch)>0)?curl_error($ch).", error code :  ".curl_errno($ch):"All good";




?>



sábado, 29 de noviembre de 2025

viernes, 21 de noviembre de 2025

Array map

 <?php

function cube($n, $r)

{

    return ($n * $n * $n) / $r;

}


$a = [1, 2, 3, 4, 5];

$c = [1, 2, 3, 4, 5];


$b = array_map('cube', $a, $c);


print_r($b);

?>

miércoles, 19 de noviembre de 2025

array filter

 $arr=[12,3,90,4];


function Myfunc($k){

return $k>80;

}

$result=array_filter($arr,"Myfunc",0);

  

  print_r($result);

sábado, 3 de mayo de 2025

last value

<?php

$arr=[13,4,91,8];


foreach( $arr as $k=>$v){

 

 if(end($arr)==$arr[$k]){

  

   echo "This is the last value $v no pending value";

   

 }

  else {

       echo  "$v  and next value is  {$arr[$k+1]} <br>";


  }

  

}

?> 

----------------

<?php

$arr = [13, 4, 91, 8];

$lastIndex = count($arr) - 1;


foreach ($arr as $k => $v) {

    if ($k === $lastIndex) {

        echo "This is the last value $v, no pending value";

    } else {

        echo "$v and next value is {$arr[$k + 1]} <br>";

    }

}

?>

13 and next value is 4
4 and next value is 91
91 and next value is 8
This is the last value 8, no pending value

sábado, 5 de abril de 2025

Class interface

 // Defining the interface

interface BicycleInterface {

    // Method declarations (no implementations)

    public function changeCadence($newValue);

    public function changeGear($newValue);

    public function speedUp($increment);

    public function applyBrakes($decrement);

    public function printStates();

}






// Implementing the BicycleInterface in a class

class Bicycle implements BicycleInterface {

    private $cadence = 0;

    private $speed = 0;

    private $gear = 1;


    // Implementing methods from BicycleInterface

    public function changeCadence($newValue) {

        $this->cadence = $newValue;

    }


    public function changeGear($newValue) {

        $this->gear = $newValue;

    }


    public function speedUp($increment) {

        $this->speed += $increment;

    }


    public function applyBrakes($decrement) {

        $this->speed -= $decrement;

    }


    public function printStates() {

        echo "Cadence: " . $this->cadence . ", Speed: " . $this->speed . ", Gear: " . $this->gear . "\n";

    }


}


// Example usage

$bicycle = new Bicycle();

$bicycle->changeCadence(50);

$bicycle->changeGear(3);

$bicycle->speedUp(20);

$bicycle->applyBrakes(5);

$bicycle->printStates();  // Outputs: Cadence: 50, Speed: 15, Gear: 3

Clsss Inheritance:

 <?php


// Parent class

class Vehicle {

    public $brand;

    public $model;

    

    // Constructor

    public function __construct($brand, $model) {

        $this->brand = $brand;

        $this->model = $model;

    }


    // Method in parent class

    public function start() {

        echo "The vehicle is starting.\n";

    }

}


// Child class inheriting from the Vehicle class

class Car extends Vehicle {

    public $doors;

    

    // Constructor in child class

    public function __construct($brand, $model, $doors) {

        // Call parent class constructor to initialize properties

        parent::__construct($brand, $model);

        $this->doors = $doors;

    }


    // Method in child class

    public function honk() {

        echo "The car is honking.\n";

    }


    // Overriding the parent method

    public function start() {

        echo "The car is starting.\n";

    }

}


// Creating an instance of the Car class

$car = new Car("Toyota", "Corolla", 4);


// Accessing inherited properties

echo "Brand: " . $car->brand . "\n";  // Outputs: Brand: Toyota

echo "Model: " . $car->model . "\n";  // Outputs: Model: Corolla

echo "Doors: " . $car->doors . "\n";  // Outputs: Doors: 4


// Calling methods

$car->start();  // Outputs: The car is starting.

$car->honk();   // Outputs: The car is honking.


?>


domingo, 23 de marzo de 2025

php class example

 class Hombre {

  private $name;

  private $age;


  // Constructor to initialize the name and age

  function __construct($name, $age = 1) {

    // If the name length is less than 3, generate a unique ID as the name

    $this->name = (strlen($name) < 4) ? $name.'_'.uniqid() : $name;

    $this->age = $age;

    echo "$this->name has been created<br>"; 

  }


  // Method to change the name

  function changeName($name) {

    $this->name = $name;

  }


  // Method to get the name

  function getName() {

    return $this->name; 

  }


  // Method to get the age if needed

  function getAge() {

    return $this->age;

  }

}


// Creating an object with the name "a" and age 34

$m = new Hombre('a', 34);  // name will be replaced with a unique ID


// Changing the name to "Mario Rodriguez"

$m->changeName('Mario Rodriguez');


// Outputting the new name

echo $m->getName();  // Outputs: Mario Rodriguez

miércoles, 19 de marzo de 2025

Insert delete function mode

 <?php

function Updatedb($query){



mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);




// Create a connection to the database


$mysqli = new mysqli("localhost", "my_user", "my_password", "world");




// Check for connection errors


if ($mysqli->connect_error) {


    die("Connection failed: " . $mysqli->connect_error);


}




// Check if table exists before creating it


//if ($mysqli->query("SHOW TABLES LIKE 'myCity'")->num_rows == 0) {


    // If the table doesn't exist, create it by duplicating the structure of the 'City' table


  //  if (!$mysqli->query("CREATE TABLE myCity LIKE City")) {


    //    die("Error creating table: " . $mysqli->error);


    //}


//} else {


  //  echo "Table 'myCity' already exists.\n";


//}




// Insert a new record into 'myCity'


//$query = "INSERT INTO myCity (ID, Name, CountryCode, District, Population) VALUES (NULL, 'Stuttgart', 'DEU', 'Stuttgart', 617000)";


if ($mysqli->query($query)) {


    printf("New record has ID %d.\n", $mysqli->insert_id);


} else {


    echo "Error inserting record: " . $mysqli->error;


}




// Close the connection


$mysqli->close();



}

//$query = "INSERT INTO myCity (ID, Name, CountryCode, District, Population) VALUES (NULL, 'Stuttgart', 'DEU', 'Stuttgart', 617000)";

Updatedb($query);

?>


martes, 18 de marzo de 2025

select function

   <?php

function select($query){


mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);  // 1 enable reporting


$mysqli = new mysqli("localhost", "my_user", "my_password", "world");  // 2 connect to the db


if ($mysqli->connect_error) {                                     // 3 check connection error

    /* Use your preferred error logging method here */

    error_log('Connection error: ' . $mysqli->connect_error);

    exit();

}


//$query = "SELECT Name, CountryCode FROM City ORDER BY ID LIMIT 3";  // 4 corrected query


// Execute the query and check for errors

$result = $mysqli->query($query); 

if (!$result) {  // Check if the query failed

    printf("Error message: %s\n", $mysqli->error);

    exit();

}


$mysqli->close();  // 5 Close the connection as soon as it's no longer needed


// Fetch results as an associative array

return $rows = $result->fetch_all(MYSQLI_ASSOC);  // 6 print result as assoc array

//foreach ($rows as $row) {

  //  printf("%s (%s)\n", $row["Name"], $row["CountryCode"]);

//}

print_r(select($query =$argv[1]\));


?>


 php select.php "select * from users;" 

 Array

(

    [0] => Array

        (

            [userId] => 60

            [phoneNumber] => 12127960900

            [accessCode] => 593161

            [pin] => 1234

            [nameURL] => https://rdasteriskrecordings.s3.amazonaws.com/12127960900.wav

            [lastCalled] => 2025-03-06

            [userLang] => en

            [userAuthMode] => cid

        )


    [1] => Array

        (

            [userId] => 61

            [phoneNumber] => 100001

            [accessCode] => 406366

            [pin] => 1234

            [nameURL] => https://rdasteriskrecordings.s3.amazonaws.com/2100001.wav

            [lastCalled] => 2025-03-06

            [userLang] => en

            [userAuthMode] => cid

        )


)


lunes, 10 de marzo de 2025

mysqi step by step

 <?php


mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);  // 1 enable reporting


$mysqli = new mysqli("localhost", "my_user", "my_password", "world");  // 2 connect to the db


if ($mysqli->connect_error) {                                     // 3 check connection error

    /* Use your preferred error logging method here */

    error_log('Connection error: ' . $mysqli->connect_error);

    exit();

}


$query = "SELECT Name, CountryCode FROM City ORDER BY ID LIMIT 3";  // 4 corrected query


// Execute the query and check for errors

$result = $mysqli->query($query); 

if (!$result) {  // Check if the query failed

    printf("Error message: %s\n", $mysqli->error);

    exit();

}


$mysqli->close();  // 5 Close the connection as soon as it's no longer needed


// Fetch results as an associative array

$rows = $result->fetch_all(MYSQLI_ASSOC);  // 6 print result as assoc array

foreach ($rows as $row) {

    printf("%s (%s)\n", $row["Name"], $row["CountryCode"]);

}


?>


sábado, 8 de marzo de 2025

sábado, 15 de febrero de 2025

SANITIZE_NUMBER

<?php 

 $nums="12a";

echo filter_var($nums,FILTER_SANITIZE_NUMBER_INT); //12


//https://www.php.net/manual/en/filter.constants.php#constant.filter-sanitize-string

//https://www.php.net/manual/en/function.filter-var.php


?>