Someone can explain to me why and when we need to reference variables and function.
example:
function &load_class()
{
}

or

$class = &new Class();

I also noticed that some php code vars sometimes appears like this:

$_var instead of $var;

there is any reason for that.

Recommended Answers

All 3 Replies

The first example you put there is a function, which can include code to execute at a later time, and can be called using the function name. This is useful for something that needs to be done multiple times in a page as you only write the code once.

function my_function(parameter1, parametar2) {
  //Do something here
}

//To call the function
my_function('foo','bar');

The second one is a class (OOP) which typically contains a group of functions. This is used for many things such as a shopping cart in an eCommerce site as the code is reusable and fairly dynamic.

Lastly, generally $_var variables are global ones such as $_POST to get data posted from a form, $_GET to get data from the query string, and $_SERVER to get data related to the server.

but the sign & is a reference right? but why you should reference your methods?

if i am not wrong, then & sign in useful when we want to call a class. i have also seen this type of functions in so many program. And in every program there was a similar thing and that was - they are calling a class when calling function....
that code can be like this....

function &load_class($class, $instantiate = TRUE) {
    static $objects = array();
    
    if(isset($objects[$class]))
    {
        return $objects[$class];
    }
 
    $name = strtolower($class);
 
    $objects[$class] =& new $name();
    return $objects[$class];
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.