-2

I don't use so far PHP use word, but must now... :)

index.php content:

require_once 'Classes/MainClass.php';
$obj = new Main();
echo $obj->test();

Classes/MainClass.php

<?php
use AdminFrontEnd;

class Main {
    function test(){
        return new AdminFrontEnd("debug");
    }
} 

AdminFrontEndClass.php content:

<?php
class AdminFrontEnd {
    function __constuctor($test){
        echo $test;
    }
} 

and final, following error:

Fatal error: Class 'AdminFrontEnd' not found in Classes/MainClass.php on line 10

Sunny Patel
  • 7,830
  • 2
  • 31
  • 46
werdf02
  • 95
  • 1
  • 11
  • 3
    `use` is only for aliasing namespaces. It does not *load* the file with the code. You still need to do that using `require` or autoloading. – deceze Nov 25 '14 at 11:07
  • Possible duplicate of [How does the keyword "use" work in PHP and can I import classes with it?](https://stackoverflow.com/questions/10965454/how-does-the-keyword-use-work-in-php-and-can-i-import-classes-with-it) –  Sep 18 '18 at 18:32

1 Answers1

1

As per comment from @deceze, you will either need to explicitly import the additional class, using a require statement, or autoload.

The use statement is for aliasing a class, and as @deceze said, can be used to pull in a class from a different namespace, or to avoid a class conflict.

Having a class called 'Main' may not be ideal. Is it a singleton, or will there be multiple 'Main's?
Maybe this class would be better named 'App'.

In the longer term you will want to learn about using namespaces, so that if you use other people's classes and plugins, you won't have conflict. I've added a solution, and also some broader info below.

To get you off the hook:

Classes/MainClass.php

<?php

require_once 'Classes/AdminFrontEnd.php';

class Main {   /*   etc...  */ 


Further reading I would recommend:

Examples for creating an autoload:

http://php.net/manual/en/language.oop5.autoload.php

You'll probably want to learn about namespaces too:

http://php.net/manual/en/language.namespaces.php

I also highly recommend reading about interoperability coding standards. It's a lot to take in to begin with, but it will help you understand the logic behind using namespaces, and autoloaders.

http://www.php-fig.org/

Tim Ogilvy
  • 1,923
  • 1
  • 24
  • 36