2

I am trying to find answer of following question:

Function world() is defined in the namespace 'myapp\utils\hello.' Your code is in namespace 'myapp'

What is the correct way to import the hello namespace so you can use the world() function?

Following is my code which I am trying but I am getting this error:

Fatal error: Call to undefined function myapp\world()

My Code:

<?php
namespace myapp;
use myapp\utils\hello;
world();

namespace myapp\utils\hello;

function world()
{
  echo 'yes world';
}
0

2 Answers 2

2

You may do this:

<?php
namespace myapp;
\myapp\utils\hello\world();

namespace myapp\utils\hello;

function world()
{
  echo 'yes world';
}

Also, read more here Using namespaces.

This is intresting:

All versions of PHP that support namespaces support three kinds of aliasing or importing: aliasing a class name, aliasing an interface name, and aliasing a namespace name. PHP 5.6+ also allows aliasing or importing function and constant names.

Simply, before PHP 5.6, you can not use use to import a function. It has to be in a class. But with PHP5.6+, you can do this:

<?php
namespace myapp;
use function myapp\utils\hello\world;
world();

namespace myapp\utils\hello;

function world()
{
  echo 'yes world';
}
Sign up to request clarification or add additional context in comments.

Comments

0
<?php
namespace myapp;
use myapp\utils\hello\world;

But you miss the class name:

<?php
namespace myapp;
use myapp\utils\hello\world; // now, you can create an instance of world

class foo
{
    public function bar()
    {
        return (new world())->yourMethod();     
    }

}

And your world class:

<?php
namespace myapp;

class world
{
    public function yourMethod()
    {
        return 'It works';     
    }
}

Be sure that you've (auto)loaded the required classes!

1 Comment

Thanks for response. But that did not work. I also created class but this answer still not worked.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.