namespace with php [duplicate]

4

I'm trying to get deeper into namespace , but in the ways I'm trying, it's giving error . Here are two ways:

My class that falls within the classes / class.php directory

namespace minhaClasse;
class classe
{
  public function testes(){
    return "ok.. retornou!";
  }
}

The index.php file that resides in the root directory

<?php
use minhaClasse\classe;
$ver = new classe();
echo $ver->testes();
?>

When I do this, the following error appears:

  

Fatal error: Class 'myClass \ class' not found in ...

Then I modified the index.php to this form

spl_autoload_extensions(".php");
spl_autoload_register();
use minhaClasse\classe;
$ver = new classe();
echo $ver->testes();

Here is the error:

  

Fatal error: spl_autoload (): Class myClass \ Class could not be   loaded in ...

    
asked by anonymous 06.11.2016 / 01:18

1 answer

9

To work with this type of code and automatically load by namespace the directories should follow the same name that are in the namespace , in your case you already have a problem the directory should be minhaClasse/classe.php or the namespace should be use classes\classe; (within the class only namespace classes; ) any one of the options may work.

Edit the namespace from your classe to classes and to use use classes\classe :

namespace classes;

class classe
{
  public function testes(){
    return "ok.. retornou!";
  }
}

In your code, change the namespace , which will work:

spl_autoload_extensions(".php");
spl_autoload_register();

use classes\classe;

$ver = new classe();
echo $ver->testes();

to names that can make it difficult to read, this can cause confusion namespace

Minimum example:

  

Thecodeofclasspastasisasfollows(notetheclasses\classeandthenameoftheCarintheimage):

<?phpnamespaceNovic;classCar{private$active=1;publicfunctiongetActive(){return$this->active;}publicfunctionsetActive($value){return$this->active=$value;}}

Inthepreviousfolder(thatis,inthetest1folder)anamespacewascreatedwiththefollowingcode:

<?phpspl_autoload_extensions(".php");
spl_autoload_register();

use Novic\Car;

$car = new Car();
echo $car->getActive();

The diretório used index.php referring to the folder and the class.

Reading:

You have here How do namespaces work in PHP? and also on PSR-4 , which is well used.

References:

06.11.2016 / 01:24