Function - Can you declare a PHP variable one scope up

De openkb
Aller à : Navigation, rechercher

Sommaire

Questions

  GOAL: Declare/set variables in the scope of the function that called the running function.   
  DETAILS:   

Hey Overflowans,

I m looking to add one last little piece of sugar to a utility that I use in a lot of my php functions. It allows me to define a flexible contract on the input of my functions. Over a few iterations, I ve gotten it pared down to a usage that looks like this:

function doSomething($param_arr){
    FPX::contract(array(
         required  => array("length", "width", "height", "weight"),
         optional  => array("circumference")
    ));
    $length = $parr[ length ];
    $width = $parr[ width ];
    $height = $parr[ height ];
    $weight = $parr[ weight ];
    $circumference = $parr[ circumference ];
    ....
}

FPX::contract() automatically grabs the $param_arr and parses it to make sure that it s compatible with the defined contract.

What I would like to do now is eliminate the need to declare each of the variables afterwards. Is there a way that I can, within the lowest function, declare variables in the scope of the function that called it? So FPX::contract() needs to be able to set variables that are in the scope of doSomething() so that I don t have to declare each of these variables. (I don t want to declare globals).

Ideally it would just look like:

function doSomething($param_arr){
        FPX::contract(array(
             required  => array("length", "width", "height", "weight"),
             optional  => array("circumference")
        ));
    ....
}

And then doSomething() would be able to access each of the variables listed in the contract as $length, $width, etc.

I m aware of the function($var0, $var1, $var2=null) syntax, but it s not very easy to use this syntax with a large number of optional variables.

Thanks, Ken

Answers

http://php.net/manual/en/function.extract.php http://php.net/manual/en/function.extract.php

That is, just have your contract() return an array or a reference to an array, then extract() it.

Source

License : cc by-sa 3.0

http://stackoverflow.com/questions/7972795/can-you-declare-a-php-variable-one-scope-up

Related

Outils personnels
Espaces de noms

Variantes
Actions
Navigation
Outils