Having a function within a snippet

Are there any other ways to have a function in a snippet when that snippet runs more than once on the same resource, besides the runSnippet API?


I don’t really understand your question, but in snippet code, the only safe way to run another snippet is with runSnippet(). The runSnippet() function always returns a string containing the return value of the snippet you call.

You can have as many functions as you like in a snippet, but I doubt if that answers your question.

If you can give some more details about exactly what you’re trying to do, we may be able to give you a better answer.


‘Function’ in Modx means little to me. The function as you say must be in some identifiable object, such as resource, snippet or chunk or maybe tv…or js or somewhere else. There are multiple ways ultimately because Modx is made to be as customizable as possible, as we recently saw, GET and SESSION data are other ways to preserve and access data within a Modx session, but they mostly need a snippet (or at least an output tpl) to actualize.

Still, Modx makes it easy to do this, this is part of the beauty of Revo, the flexibility and the security are always the key points.

There must be a delivery method for the function I think. I’ve been wrong before :stuck_out_tongue:

1 Like

I suppose your problem is you want to define a funtion in the snippet’s PHP code and want to avoid an error when it is defined more than once due to multiple calls of the snippet on the page.

In this case, you can use the “function_exists()” PHP function like this:

if (!function_exists('A')) {
    function A() {
        // function A implementation

@jcreiss is correct. I’ve had this problem before.

Wrap the function in a function_exists statement, or simply avoid doing function definitions within snippets which is kind of an anti-pattern in MODX. Instead do a require_once on a PHP file, or define a class and use that as a singleton, etc.


My usual practice for any snippet that needs one or more functions in it is to create a class file, then in the snippet, just load the class file, instantiate the class, and call it’s methods at will.

Wrapping the function in a function_exists statement can come back to bite you if some other snippet has a function with the same name but different code and runs ahead of yours. It won’t happen often, but when it does, it will be a nightmare to diagnose and fix.


thanks guys, those suggestions really helped

1 Like