We launched new forums in March 2019—join us there. In a hurry for help with your website? Get Help Now!
    • 15001
    • 697 Posts
    Hi,

    I’m writting a snippet and observed that the "$modx" object cannot be accessed from within a function inside my snippet. I’m surprised that it is not global.
     $temp = $modx->getDocumentObject('id',183);

    is ok in the snippet core.

    When put inside a function in the snippet I get :
    Fatal error: Call to a member function getDocumentObject() on a non-object
    Any idea how to handle this ?

    Should I do something like :
    global $modx2 = $modx;

    and in function
    $modx2 = getDocumentObject(...

    or pass the $modx object as parameter of the function ?
    I assume that the $modx object is quite large. Isn’t it ?

    Thanks for your help.
      • 15001
      • 697 Posts
      Seem that the solution is adding this in the function :
      global $modx;

      An example is available here with the getParents() function in the snippet:
      http://modxcms.com/forums/index.php/topic,25827.0.html
        • 3749
        • 24,544 Posts
        If you refer to a variable inside a PHP function, PHP assumes that you want a local variable whose scope is that function, *unless* you declare it as global at the top of the function, in which case, PHP knows that you mean to refer to the global variable defined outside the function. smiley

          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
          • 15001
          • 697 Posts
          @Bob: Thanks for this interesting explanation.
          I had not tried it by fear to overwrite the modx object as it would happen with other programming languages, until I saw an example.
            • 3749
            • 24,544 Posts
            Glad you got it working. PHP does take some adjustment for those of use arriving from other languages (C++ in my case). wink

              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