problem with namespace when running project

Asked

Viewed 830 times

1

I cannot make this code run, I am starting with namespace and would like to give me a tip to continue my studies.

First class

<?php

namespace view\classes;
class View {
    public function visualizar()
    {
        echo 'visualizar';
    }
}

Second class

<?php
namespace view\classes;
class ScriptView extends ViewClass{

    public function visualizar(){
        echo 'visualizar';
    }

}

$script = new ViewClass();
echo $script ->visualizar();

2 answers

1

Where is the definition of the class "Viewclass"? Assuming you misspelled you extending the View will not work as the file containing its definition is not being included in the file it uses (Scriptview class).

In the class definition file Scriptview you need to include the class definition file View.

How will you use namespace you must use the resource of self-loading that will do the job of including these files for you using namespace as masks to directories.

For example:

namespace Myframework Base Controller;

When you use the class that is in this namespace, in the Controller example, PHP will provide the name of that class you want access to and you will point to the physical file that will be included:

Myframework/Base/Controller.php - (these extension settings and extra directories can be set in your autoload).

Here you find the link of the function that allows you to register autoload and example how to implement your own autoload.

Besides the fact that you don’t need to include your files manually you get a performance gain by not including unused classes, that is, the loading of these classes will be on demand.

  • Thank you very much.

1


Because it has two distinct files, php will not automatically recognize both classes.

You need to use an autoload for one class to "run" the other.

Folder structure:

view
 |_ classes
     |_ View.php
     |_ ScripView.php
index.php

In your file index.php implement the autoload and fly-there!

<?php

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

use view\classes\ScriptView;

$script = new ScriptView(); // ou new view\classes\ScriptView();
$script->visualizar();

In that case note that:

  1. Folder structure follows exactly what defined by namespace
  2. Some operating systems differ from lower case, so try to maintain a pattern of names between directories and namespaces.
  3. Your class ScriptView in the extende example ViewClass, that doesn’t exist.

More information:

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

http://php.net/manual/en/function.spl-autoload-register.php

  • Thanks a lot man!

Browser other questions tagged

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