problem with namespace when running project

1

I can not get this code to run, I'm starting with the namespace and would like a tip for me 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();
    
asked by anonymous 15.08.2014 / 02:14

2 answers

1

By having two separate files, php will not automatically recognize both classes.

You must use an autoload for one class to "populate" the other.

Folder structure:

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

In your index.php file, implement autoload and fly it!

<?php

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

use view\classes\ScriptView;

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

In this case note that:

  • The folder structure follows exactly the namespace defined
  • Some operating systems are case-sensitive, so try to maintain a pattern of names between directories and namespaces.
  • Your class ScriptView in the example extends ViewClass , which does not exist.
  • More information:

    link

    link

        
    15.08.2014 / 02:39
    1

    Where is the "ViewClass" class definition? Assuming you typed in wrong you extending the View will not work, because the file containing your definition is not being included in the file it uses (ScriptView class).

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

    As you will use namespace you should use the autoloading feature that will do the work to include these files for you using the namespace as masks to the 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 to which you want access and you will point to the physical file that will be included:

    MyFramework / Base / Controller.php - (These extension definitions and extra directories can be defined in your autoload.)

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

    In addition to the fact that you do not need to include your files manually you have a performance gain by not including unused classes, ie loading these classes will be on demand.

        
    15.08.2014 / 02:36