nick nick - 17 days ago 4
PHP Question

Don't understand php namespace, how can I call function from another class?

I am trying to use Azure storage for php, the setup steps are to include the namespace, include composer autoload and then use the azure classes, so I have the following. However further down I use the class Microgrid and it's not found because of the namespace, it is in a different directory. How can I use other classes that aren't part of that namespace? Also, what's the correct way to specify your namespace path? It's in a different directory relative to the page this is for and the one I am using is not at the root, should I start at the root?

namespace MicrosoftAzure\Storage;
use \MicrosoftAzure\Storage\Common\ServicesBuilder;
use \MicrosoftAzure\Storage\Blob\Models\CreateContainerOptions;
use \MicrosoftAzure\Storage\Blob\Models\PublicAccessType;
use \MicrosoftAzure\Storage\Common\ServiceException;

require_once '/var/www/html/vendor/autoload.php';


$action = MicroGrid::GetParameter('action');

Answer

ClassNames are considered relative to the current namespace unless they start with a \

This means that inside the MicrosoftAzure\Storage namespace you can use the relative namespace for class.

If you want to call a class from a different namespace you should call fully-qualified name for it like

$action = \MicrosoftAzure\WhereEver\MicroGrid::GetParameter('action');

or use the name space or unique class with fully-qualified name

use \MicrosoftAzure\WhereEver;

or

use \MicrosoftAzure\WhereEver\MicroGrid;

then:

$action = MicroGrid::GetParameter('action');

Edited to make it clear

namespaces allow us to avoid naming collisions and to alias long names caused by avoiding naming collisions.

it depends to your autoloader for a simple example I create a new project and make this autoloader in the index.php located at root directory

function __autoload($className){
    //if it's a full name with windows style slashes correct the path
    $file_name = str_replace('\\', '/', $className);
    require_once("vender/src/".$file_name.".php");
}

when I call $date = new \App\Utility\Date(); autoloader will require this file:

verdor/src/App/Utility/Date.php

and in Date.php I used this name space namespace App\Utility;