2

I'm playing with a CMS that utilizes Namespaces and I'm trying to make use of it instead of including files and using functions within those files.

From what I understand and have tried, I have a file loaded as a PSR-4 with a declared namespace, class, and a function inside that I'd like to access. It looks like:

namespace MyFunctions;

    class basic {

        function say_hello($a) { 
            echo "Hello, $a"; 
        }

    }

And from another file, I can see that the "MyFunctions" namespace is indeed loaded when checking using the get_declared_classes() function. However, I'm completely lost with how to use the "say_hello()" function.

I've tried:

use MyFunctions;

// instantiate class
$a = new basic();

// this gives me 'call to undefined function'
echo say_hello("Bob");

I've tried digging at other examples and I'm chomping at the bits trying to access this function. Could someone give me an example of how I would get to, and use, the "say_hello()" function from another file? Any help would be HUGELY appreciated, thanks!

1
  • Even though a class is namespaced, you still need to instantiate it before accessing its methods` Commented Jan 17, 2015 at 0:33

1 Answer 1

3

With the setup you have here. You would have to execute the following to fire that function.

(new MyFunctions\basic)->say_hello("Bob");

(I dont recommend this method, it creates an object for no reason.)

What I'm assuming you wanted was:

namespace MyFunctions;

function say_hello($a)
{
    echo "Hello, $a";
}

at which point you could use

// this gives you 'Hello, Bob'
MyFunctions\say_hello("Bob");
Sign up to request clarification or add additional context in comments.

1 Comment

The latter example was exactly what I needed! I guess I was largely confused by the Class itself which I didn't need.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.