Call user function for magic method PHP

by frank on August 11, 2010

in Tips of the Week

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.


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.

Was this article useful?

rss feed icon

Email this article to yourself or...

rss feed icon

Subscribe to the RSS feed for more useful articles and tips.

Share this article with others

  • del.icio.us
  • Twitter
  • Reddit
  • StumbleUpon
  • Facebook
  • Digg