Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have a function that is called once for initiation, and then later as a callback. I need some of the values that were defined in the initial setup to be accessed in the callback.

I am unsure of exactly what happens to the variables in the 'init' section after it closes. Clearly the static is available to the callback section when it is called. However is the object available as well? Or is it unset after the 'init' section returns? If it is lost, is it possible to assign an object to a static variable? Such as $static = $object; before the return; line?

function someFunction($type) {
    if ($type == 'init') {
        static $static;
        $object = new stdClass();
        $object->property = 'value';
        return;
    }
    elseif ($type == 'callback') {
        //Stuff that uses $object->property
        return;
    }
}
share|improve this question
1  
Why haven't you tried it? –  phant0m Jun 19 '13 at 17:09
1  
Why isn't this a class? –  Paolo Bergantino Jun 19 '13 at 17:09
    
@PaoloBergantino why should it be? –  Foo_Chow Jun 19 '13 at 17:31
1  
@Foo_Chow: Because you have all the features of a class implemented into a function, and that doesn't really work well - otherwise you wouldn't have asked. –  Sven Jun 21 '13 at 18:12
add comment

1 Answer

up vote 1 down vote accepted

Your function as a class:

class Foo
{
    private $static;

    public function __construct()
    {
        $object = new stdClass();
        $object->property = 'value';

    }

    public function callback()
    {
        //Stuff that uses $object->property
        return;
    }
}

Usage:

$array = array(); // completely useless array

$callback = new Foo();

// Use the callback object for a callback:
array_walk($array, array($callback, 'callback'));

As you can tell: The constructor does not save the $object, but it would be very easy to save it to a property of the Foo class if needed. It would then be available to any other function call inside this class.

share|improve this answer
    
fair enough, so in other words, even if it is possible to store an object in a static, it would make for unusual code and it is best to stick with tried and true practices. Thanks. –  Foo_Chow Jun 21 '13 at 19:32
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.