Question

Extract function of php adds variables to the local scope of the calling function. How can we write our own php function extract which does the same?

Was it helpful?

Solution

I don't think you can do that in pure-PHP : a function doesn't have access to the variables of its caller.

This looks like the sort of thing you'll need to write a C extension to develop -- you'll have more control over the internals of PHP variables there.

(And I don't really see why you're trying to do that : why not just use the existing extract function ? )

OTHER TIPS

PHPJS is a javascript library which contains the functions as those of php, here is its extract function you can get an idea from. Having said that, i wonder why are you looking for your own function when php already provides one.

Ok, if it is just for the fun of it it is possible:

<?php
$data=array('a' => 1, 'b' => 2);

foreach ($data as $name => $value) {
    ${$name} = $value;
}

echo $a;
?>

But some problems - like conflicts with $data, $name and $value and you can't wrap it in a function. But possible.

Yes it is possible,

the reason why i did this because i need something more from extract function that it should trim the values too

function extractArray($ar) {
        if(count($ar)>=1) {
            foreach($ar as $k=>$v) {
                $GLOBALS[$k] = (is_array($v)?$v:trim($v));
            }
        }
}

I just pas my $_GET, $_POST, and else arrays like this for e.g. $_GET['username'] = ' justnajm '; extractArray($_GET);

and i can just echo and it will print 'justnajm'

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top