namespace com php

Asked

Viewed 501 times

4

I’m looking to dig deeper into namespace, but the ways I’m trying, it’s giving error. Follows below the two forms:

My class inside the directory classes/class.php

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

The index.php file that is 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 'myClose class' not found in...

Then I modified index.php to this form.

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

Then comes that mistake:

Fatal error: spl_autoload(): Class myClose class could not be Loaded in...

1 answer

9


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

Edit the namespace of his classe for classes and to use use classes\classe:

namespace classes;

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

and in your code, make changes to namespace, that will work:

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

use classes\classe;

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

Observing: the names of namespace and pastas (that must have the same name) could follow names as simple as possible and without reference to names that can make reading difficult, this can cause confusion classes\classe


Minimal example:

inserir a descrição da imagem aqui

The code of the class Car is as follows (observe the namespace and the name of diretório in the image):

<?php

namespace Novic;

class Car 
{
    private $active = 1;

    public function getActive()
    {
        return $this->active;
    }
    public function setActive($value)
    {
        return $this->active = $value;
    }
}

inside the previous folder (i.e., in the folder Test1) a index.php with the following code:

<?php

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

use Novic\Car;

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

The namespace used Novic\Car referring to folder and class.


Reading:

You have it here on the website How namespaces work in PHP? and also on PSR-4, that is well used.

References:

  • 1

    It worked Virgil. Thank you very much for the clarifications and indication of reading.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.