Hey, I'm Alex, from Alex Web Develop. I hope you are having a fantastic week.
Let's talk about variable variables in PHP.
A variable variable is a PHP variable whose name is
contained in another variable. For example, let's first define a standard variable containing the string "city":
$var = "city";
Now, you want to define a new variable named $city. But instead of defining it the normal way, you want to use the string inside $var, "city", as the name for the new variable. To do that, you need to add two $ symbols before the variable that contains the name. Like this:
$$var = "London";
/* It's the same as: $city = "London"; */
In $$var, $var is replaced with its content (the string "city"), and the extra $ turns "city" into $city. Therefore, writing $$var is the same as writing $city:
The above code echoes the variable defined in the "var" request element, if set. For example, if you call the script with the "var=title" request string, it will echo: "my book title".
However, you can see how this solution is poorly readable and, in some cases, it can also have security issues.
In my opinion, it is better to use associative arrays instead:
As of PHP 8.1.0, you can mark class properties as readonly. You can initialize a readonly property only once (ex. from the class' constructor). After that, it behaves like a constant and you can't change it anymore. This only works for typed properties.
For example:
class Car { public readonly string $model; public function __construct(string
$model) { $this->model = $model; } }
$car = new Car("Civic"); echo $car->model; // "Civic";
// Error! $car->model = "new model";
WEEKLY CHALLENGE
Here's a PHP code challenge for you. You take a flight from France (or any other place you like) to Peru (or any other place you like). The flight takes 10 hours, 15 minutes and 7 seconds.
Write a PHP function that takes in input the local departure datetime and prints the local (at the arrival's place) landing datetime.