0

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;
    }
}
4
  • 1
    Why haven't you tried it? Commented Jun 19, 2013 at 17:09
  • 1
    Why isn't this a class? Commented Jun 19, 2013 at 17:09
  • @PaoloBergantino why should it be? Commented Jun 19, 2013 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. Commented Jun 21, 2013 at 18:12

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.