>/D_
Published on

Call user function for magic method PHP

Authors
  • avatar
    Name
    Frank
    Twitter

Put a bit of work into upgrading the blog and might as well make a quick post now. Heres a trick to test if a class variable exists, isset or has a particular value dynamically. Call the magic method __get() for the variable name which you can generate on the fly.

[ad#ad-1]
For example, in SilverStripe I have a class with fields NewsBoxTitle, TermsBoxTitle, ServicesBoxTitle etc. and in the template I need a control to test if the title and content is set for the Services box say, I can't access those fields dynamically using $this->$$varTitle so using call_user_func() works instead.

   /**
     * Helper function indicate if content exists for a given box
     *
     * @param String $boxName Name of box
     * @return Boolean
     */
    public function boxExists($boxName) {

        $varTitle = $boxName.'BoxTitle';
        $title = call_user_func(array($this, '__get'), $varTitle);

        $varContent = $boxName.'BoxContent';
        $content = call_user_func(array($this, '__get'), $varContent);

//        SS_Log::log(new Exception($boxName), SS_Log::NOTICE);
//        SS_Log::log(new Exception($title), SS_Log::NOTICE);
//        SS_Log::log(new Exception($content), SS_Log::NOTICE); 

        if (!empty($title) && !empty($content)) {
            return true;
        }
        return false;
    }

Just a quick tip, hope that helps.