Question

How can I set a default variable to a function in PHP? In python, it would look like this:

def fun(con = predefined):

I've tried the following to no avail:

function fun($con = $GLOBALS['con']){}

In this instance, as you can see, I would like to set the value to the definition of a global variable.

Était-ce utile?

La solution 2

Looks like your problem is that you're trying to set a default from a global. PHP may not like this. You can circumvent it this way:

function fun($con = null){
    $con or $con = $GLOBALS['con'];
}

I personally think this is kind of hokey. It looks like you're wanting to get a DB connection from a global resource. I don't think that's how this should be done, but this answer would allow $con to be set from global if not passed to the function. Or allow it to be used if passed.

Autres conseils

This is a very simple example:

 <?php
 function makecoffee($type = "cappuccino")
 {
     return "Making a cup of $type.\n";
 }
 echo makecoffee();
 echo makecoffee(null);
 echo makecoffee("espresso");
 ?>

The above example will output:

Making a cup of cappuccino.
Making a cup of .
Making a cup of espresso.

We build a small class to use the globals in a static way

class globy{
    static public function set($name, $value) { $GLOBALS[$name] = $value; }
    static public function get($name)         { return $GLOBALS[$name]; }
}

then you can do this

function fun($con=globy::get('con')){}

or you can do this (not your question)

function fun($con=globy::set('con','value_of_con')){}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top