We launched new forums in March 2019—join us there. In a hurry for help with your website? Get Help Now!
    • 3467
    • 10 Posts
    I have a plugin in which som events should run a function, like:
    function myFunction()
    {
      $result = $modx->db->select("*", "modx_site_content","");
    }
    
    
    $e = &$modx->Event; 
    switch ($e->name) 
    { 
      case "OnDocFormSave":
      myFunction();
      break;
    }
    
    


    This results in an error "Call to a member function select() on a non-object in [..] document.parser.class.inc.php(745) : eval()’d code on line 3"
    If I just try to get something like
    function myFunction()
    {
     $path = $modx->config['base_path'];
    }
    

    $path remains empty.

    What am I doing wrong?
      • 26903
      • 1,336 Posts
      You could try putting ’global $modx’ at the top of your function, so it can see the $modx object, however in my experience this doesn’t always work, I’ve called external php code from snippets where this doesn’t seem to work, try it anyway, it may be OK in a plugin.

      Like this :-

      function myFunction()
      {
      global $modx;
      $result = $modx->db->select("*", "modx_site_content","");
      }
        Use MODx, or the cat gets it!
        • 3467
        • 10 Posts
        Thanks, that did the trick. I thought I’d already tried that, but apperantly not tongue
          • 3749
          • 24,544 Posts
          Right. The scope of the $modx variable doesn’t reach inside functions so without global $modx, PHP creates a new variable called $modx that’s empty and not very useful. global $modx tells PHP that you mean the variable created outside the function.

          I’ve also encountered situations where it doesn’t work (nested includes/functions I think), but have never had the time to track down why and usually just pass the $modx variable down as an argument.
            Did I help you? Buy me a beer
            Get my Book: MODX:The Official Guide
            MODX info for everyone: http://bobsguides.com/modx.html
            My MODX Extras
            Bob's Guides is now hosted at A2 MODX Hosting
            • 26903
            • 1,336 Posts
            Yes, passing $modx as a variable is what I ended up doing, but like you say I never really sussed why sometimes you need to do this.
              Use MODx, or the cat gets it!