Blog de programación, errores, soluciones

Chose Language:
comments
Author: Admin/Publisher |finished | checked

Variables variables, variable functions and variable object ($$)

We will explore the use of $$ for various purposes in PHP programming.

Contents:

  • Introduction
  • Variable variables
  • Variable Functions or variable function names
  • Variable Objects or, more accurately, instance of variable objects

Introduction

Making the name of a function or an object variable gives us certain flexibility in using functions and objects in ways that may not have been considered before. If you’ve already read the previous PHP-101 topics or understand what a function and an object are, we’ll now discuss how to make them variable.

Variables variables

According to the PHP manual, to create a variable variable, you must do the following:

Variables varaibles
$home = "HappyDreams";
$$home = "casa en las afueras de la ciudad de Michigan";
//$$home es igual a poner $HappyDreams
//$HappyDreams contiene el valor de "casa en las afueras de la ciudad de Michigan"

The explanation regarding variable variables in PHP when using arrays is correct. Variable variables can indeed behave differently when dealing with arrays, as you need to explicitly indicate whether you are referring to the variable or to a specific index within the array.

Examples Explained:

$$casas["nombreCasa"] is ambiguous because it doesn’t clearly indicate if the variable itself or the array index is being referenced.

To specify that you want to refer to the variable $casas, and then access the array index, you should use:

${$casas}["nombreCasa"]

If you want to refer to the array index ["nombreCasa"], the correct syntax would be:

${$casas["nombreCasa"]}

This distinction ensures that the PHP interpreter knows exactly what part of the expression you’re working with—whether it’s the variable itself or an index of the array. This use of curly braces {} makes it explicit and avoids confusion.

Variable functions

In a function, it’s simple: having several functions, we can decide which one to use by calling $name();, which allows us to call the desired function.

Example: a simple calculator.

funciones variables
<?php
error_reporting(E_ALL); 
ini_set("display_errors", 1); 
function restar($args){
    $resta = 0;
    foreach($args as $key => $valor){
        if($key == 0){
            $resta = $valor;
            continue;
        }
        $resta -=$valor;
    }
    return $resta;
}
function sumar($args){
    $suma=0;  
    foreach($args as $valor){
        $suma +=$valor;
    }
    return $suma;
}

    $args=[10,4];
    $function = "sumar";
    echo "la suma de a + b es :".$function($args)."<br/>";
    $function = "restar";
    echo "la resta de a - b es: ".$function($args)."<br/>";

Keep in mind that if I use $function, I could avoid using an if or switch statement, as I directly call the function. If the value came from an HTML form, I could use a try-catch block around $function() to handle cases where the function might not exist.

Variable objects, or more precisely, variable instances of objects.

Object instances can also be variable. For example, given a URI, we could instruct the system to instantiate a specific object.

For instance, if we have the URI: localhost/miproyecto/index.php/usuario/nuevo, we could tell the system to invoke the usuario controller and the nuevo function, ensuring to wrap it in a try-catch block in case the controller or function doesn’t exist, triggering an appropriate error.

index.php / Objetos variables
<?php
error_reporting(E_ALL); 
ini_set("display_errors", 1); 

class car{
    function show(){
        return "A fake car";
    }
}

$URL = $_SERVER['REQUEST_URI'];
$myindex = __DIR__."/";
$URL = substr($URL,strpos($URL,"index.php") + 10);

$result= explode('/',$URL);
$obj = $result[0];
$function = $result[1];

try{
    $controller = New $obj();
    echo $controller->$function();
}catch(Exeption $e){
   echo $e;
}

Very basically, this is how a modern MVC framework works today. If we take a framework like CodeIgniter and look at its main index.php, it would likely have something similar to what was previously described, although more complex.

See: routing in PHP.

Category: en-php
Something wrong? If you found an error or mistake in the content you can contact me on Twitter | @luisg2249_luis.
Last 4 post in same category

Comments