Calling Controller (App.php) functions from setup.php (and other controllers)

Here’s a reply I wrote a bit ago that might help you out with understanding namespaces: Controller namespace issue, different behavior on localhost and development server (solved?)

Finding out what namespace a class, method, or function is in is generally pretty simple:

  • Find the file where the function/method/class is defined
  • Go to the top of the file and look for namespace
  • If you’re looking for a…
    • function then that’s it, just prepend the namespace when calling the function
    • class then that’s it, just prepend the namespace when calling the class
    • method then you’ll need to prepend the namespace, then class, when calling the method

Take the example file below:

<?php

namespace Roots;

class Sage {
    public static function hello()
    {
        return 'hello from a method';
    }
}

function goodbye()
{
    return 'goodbye from a function';
}

To instantiate this class in another file, you would write:

$class = new Roots\Sage();

To call the static method hello() from another file, you would write:

$greeting = Roots\Sage::hello();

To call the function goodbye() from another file, you would write:

$farewell = Roots\goodbye();

If the other file has a namespace, and that namespace is not Roots, then you need to prepend a slash to all of your calls, i.e.:

$greeting = \Roots\Sage::hello();

That should be enough info to get you started.

6 Likes