php

How to return a variable by name from a function in PHP

In this tutorial, we’re going to see how the result of a function can be used as a name for a variable in PHP.

The name of variables can be specified depending on the return value of a function. The syntax for this is:

${ foo() } = ...;

Where foo() is any function that must return a value that is a string or at least can be converted to a string. (By the way, even an empty string may be returned).
 

How to return a variable by name from a function in PHP

In this example the function foo() returns the name of the variable, which is “bar”. The value “lorem” is assigned to this variable.

<?php
    function foo() {
        return 'bar';
    }
 
    ${foo()} = 'lorem';
    var_dump( ${foo()} );   //display: lorem
    var_dump( $bar );       //display: lorem
?>

Output:

string(5) "lorem"
string(5) "lorem"

 

PHP MCQ - Multiple Choice Questions and AnswersPHP Questions and Answers – Object-Oriented OOP – Part 1This collection of PHP Multiple Choice Questions and Answers (MCQs): Quizzes & Practice Tests with Answer focuses on “Object-Oriented OOP”.   1. The concept of…Read More mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *