Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

export variable to previous scope in PHP

Tags:

scope

php

Now, before you jump at how you shouldn't mix scopes: I realize this. However, this is a case where either scope mixing must occur or major code duplication must occur—nothing around it. And I'd prefer scope mixing.

That said, I'd like this code:

function a() {
    $a = "a";
    $b = "b";
    $c = "c";
}
function b() {
    a();
    echo $a . $b . $c;
}
b(); // Output: abc
echo $a; // Should raise a notice that $a is undefined

to be able to work as commented. I know it's not possible in most languages—I was able to do it in Ruby, though; and wonder if you can do it with PHP.

The names of variables aren't known beforehand in the real situation.

Again, it's code duplication or this—absolutely no way around it.

Also, it'd be okay if a had to be something like a('b') or something.


In reality, the code is this:

static function renderError($what, $vararray) {
    foreach($vararray as $key => $val) { /* this foreach is the code we want to decouple */
        $key = 'e_'.$key;
        $$key = htmlspecialchars($val);
    }
    ob_clean();
    exit(eval('?>'.file_get_contents(ROOT."/templates/$what.php")));
}

With a call like E_Render::renderError('NotFound', array( 'requested_url' => '/notfound', 'misspelling' => '/reallynotfound' ));

Then, in templates/NotFound.php, you'd have something like:

<html>
<body>
<?php echo $e_requested_url; ?> could not be found. Did you mean <?php echo $e_misspelling: ?>?
</body>
</html>

We'd really rather not have our template authors do anything more than that...although $e['requested_url'] could be done if nothing better was available.

like image 884
Aaron Yodaiken Avatar asked Sep 19 '26 12:09

Aaron Yodaiken


1 Answers

That's why we have OO:

class Foo {

    function a() {
        $this->a = "a";
        $this->b = "b";
        $this->c = "c";
    }

    function b() {
        $this->a();
        echo $this->a . $this->b . $this->c;
    }
}

$f = new Foo;
$f->b(); // Output: abc
echo $a; // Should raise a notice that $a is undefined

Alternatively:

function a() {
    $a = "a";
    $b = "b";
    $c = "c";

    return compact('a', 'b', 'c');
}

function b() {
    extract(a());
    echo $a . $b . $c;
}

See: compact(), extract()

Otherwise I don't see a way of doing this without drastically changing the language.

PS: If you feel this feature is so important, why don't you just use Ruby?

like image 171
NullUserException Avatar answered Sep 22 '26 01:09

NullUserException



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!