Reputation: 2319
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';
}
Upvotes: 2
Views: 449
Reputation: 2307
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';
}
Upvotes: 2
Reputation: 5796
<?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!
Upvotes: 0