Page 1 of 1

use class in external namespace

Posted: Tue Jun 14, 2016 12:44 pm
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.

Re: use class in external namespace

Posted: Tue Jun 14, 2016 4:10 pm
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.

Re: use class in external namespace

Posted: Wed Jun 15, 2016 9:28 am
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();
}
}
?>