3

I recently learn how to use namespaces on the official site. However, it is not working for me.

I have created 2 files below to test.

Example/ExampleClass.php

<?php  
namespace Example;

class ExampleClass {

    public function __construct(){
        echo 'Example Class is used by namespace';
    }
}

main.php

<?php 
use Example\ExampleClass as ExampleClass;

$example_class = new ExampleClass;

When I complied, I got

This page isn’t working localhost is currently unable to handle this request. HTTP ERROR 500

This may be a stupid question but what is wrong with the code?

1 Answer 1

2

You missing include or require in your main.php script:

include_once('Example/ExampleClass.php');

use doesn't include anything. It just imports the specified namespace (or class) to the current scope if they are before included

Sign up to request clarification or add additional context in comments.

7 Comments

Is there any way to just use namespace without include or require? Something like include or require every time when namespace is used.
Nope. At least one time you must included it.
About your HTTP 500 Error this can be another issue. In my environement if I not include ExampleClass.php ... I got Fatal error: Uncaught Error: Class 'Example\ExampleClass' not found ... So I have tried your ExampleClass and work as espected (if I have included it first)
Abut include You have one posibility to automatize Take a look here (see examples): php.net/manual/en/language.oop5.autoload.php
I have restarted the browser and it seems to work now. Thank you very much for your help.
|