How do I use to call another namespace without using include?

Asked

Viewed 203 times

0

I see programmers all the time using the "use" command below the "namespace" command without first using a include.

An example is the Medoo library:

namespace Medoo;

use PDO;
use Exception;
use PDOException;

class Raw {
    public $map;
    public $value;
}

How does it work? I try to do the same but it never works.

Take my example and explain to me, please, what’s wrong:

Directories:

App
|
+--- MyspaceA
|       |
|       +--- MyclassA.php
|
+--- MyspaceB
|       |
|       +--- MyclassB.php
|
+--- index.php

Myclassa.php:

<?php namespace MyspaceA;

    class MyclassA {
        public static $myvarA = "Ola Mundo";
    }

?>

Myclassb.php:

<?php namespace MyspaceB;

    use MyspaceA\MyclassA;

    class MyclassB {
        public static $myvarB = "!!!!!";
    }

    $myvarC = MyclassA::$myvarA + MyclassB::$myvarB;

?>

index php.:

<?php 

include("MyspaceA/MyclassA.php");
include("MyspaceB/MyclassB.php");

echo($myvarC);

?>

The result I’ve been waiting for:

Ola Mundo!!!!!

But it makes a mistake!

What’s wrong with my code?

  • Take a look at the yellow box links above your question, the answers there should clarify your question. Otherwise, let us know here.

  • So, actually, I’ve seen these answers, but I found them VERY complicated! They involve Poser and super theoretical explanations of spl and such. I wanted something very simple, well beans and rice, to make these Clases work with as little code as possible.

  • You need to implement an autoloader (don’t be scared that the function starts with spl_). William’s answer in the linked question shows how. Something else, his $myvarC is global, in PHP namespaces do not include variables.

  • I really don’t understand... I know how to use autoload. What I don’t understand and doesn’t work with me is using a USE command below the NAMESPACE command.

  • Ok. Please edit the question and explain what is going wrong in your example. Then I can reopen the question. Because I didn’t understand what you didn’t understand :). The use you need to use every time you have to use classes that come from another namespace.

  • Well... then maybe this is the right question: What commands do I need to write in the index.php file for the USE command under NAMESPACE in Myclassb.php to work? I may have to use a __autoload command on index.php. And, at other times, I have already used the __autoload command successfully. But I can’t ever make the command use to load another class through __autoload, so I’m writing something wrong. But I don’t know what. <<< Does this edition serve?

Show 1 more comment
No answers

Browser other questions tagged

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