use class in external namespace

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
tedschw
Forum Newbie
Posts: 2
Joined: Tue Jun 14, 2016 12:26 pm

use class in external namespace

Post by tedschw »

Hi,

I'm new to PHP and am having trouble including one class in another with the "use ..." keyword. Both classes have different namespaces and reside in different files.

I can't get past a class not found error. Here is simple example of what I'm trying to accomplish:

file structure (i.e., files in same directory):
C:\
- app.php
- util.php

File app.php:

<?php
namespace App;
use Util\util;

$myUtil = new util();
$myUtil.doIt();
?>

file util.php:

<?php
namespace Util;

function doIt(){
phpinfo();
}
?>

When I attempt to execute, I see this error:

$ php app.php

Fatal error: Uncaught Error: Class 'Util\util' not found in C:\TestPHP\app.php on line 7

Error: Class 'Util\util' not found in U:\apps\TestPHP\app.php on line 7

Call Stack:
0.0000 350544 1. {main}() U:\apps\TestPHP\app.php:0

PHP Fatal error: Uncaught Error: Class 'Util\util' not found in C:\TestPHP\app.php:7
Stack trace:
#0 {main}
thrown in C:\TestPHP\app.php on line [/inline][/inline]7

Can anyone shed light on what I'm doing wrong? I want to continue to employ the "use <class>" directive, because I have some third-party code which is implemented this way.
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: use class in external namespace

Post by requinix »

"use" will not autoload class files - you have to do that part yourself. Or, in the case of your very small example, require() the file manually.
tedschw
Forum Newbie
Posts: 2
Joined: Tue Jun 14, 2016 12:26 pm

Re: use class in external namespace

Post by tedschw »

Thanks, that helped. I ultimately had to also define classes within my files. I could then "use" the alias to the class as I had wanted:

app.php:

<?php

namespace APP;
require "util.php";
use Util\util;

class app extends util{}
$app = new app();
$app->doIt();
?>

util.php:

<?php
namespace Util;

Class util {
function doIt(){
phpinfo();
}
}
?>
Post Reply