Jump to content
fruid

no access to API inside custom function

Recommended Posts

namespace ProcessWire; 
function myfunction() {
echo $config->paths->assets; // Notice: Undefined variable: config (…)
}

can't access the API inside a custom function. Didn't have that problem before.

This seems like a basic setting. What could be the reason?

Share this post


Link to post
Share on other sites
2 hours ago, fruid said:

Didn't have that problem before.

Nope. It's never been possible. You must be confusing this with something else. Nothing to do with ProcessWire. Many (most?/all?) languages have variable scope. $config is outside the variable scope of myfunction(). myfunction() doesn't know what config is. You have to tell it. Having a namespace declaration has nothing to do with it.

namespace ProcessWire; 
// alternative 1: use the global wire() function - @see: https://processwire.com/api/ref/functions/wire/
function myfunction() {
echo wire('config')->paths->assets; // no error
}
// alternative 2: pass in $config
function myfunction2($config) {
echo $config->paths->assets; // no error
}

alternative 3: functions API - e.g. https://processwire.com/api/ref/functions/config/ @see also: https://processwire.com/api/ref/functions/

Edited by kongondo
  • Like 5

Share this post


Link to post
Share on other sites
On 9/19/2020 at 6:59 PM, fruid said:

it doesn't know $page or $pages either…

it doesn't work for the same reason $config doesn't work, use wire('page') inside functions

Share this post


Link to post
Share on other sites

In PHP functions do not inherit variables from the parent scope. Even closures (unlike many other languages) don't do so unless explicitly stated by `function() use ($var, …) {}`

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Recently Browsing   0 members

    No registered users viewing this page.

×
×
  • Create New...