happy cat image

everdevel

coding

login
NotificationX
  • Currently, only notices of comments are displayed.
  • no comment or please login

namespace

Declaring a function with the same function name in one web page will result in an error.
This is the same as you cannot have the same file in a folder.
You can't have two b.php files in a folder called a, but you can put a b.php file in a folder and create a folder called b.php.
The reason I mention folders is because they are easier to understand when you think of namespaces as folders. An error occurs if you use the function name with the same name as follows:

<?php
    function hello(){}
    function hello(){}
?>

Result of the code above

An error occurs as shown above. Let's use the namespace above to avoid errors.

How To Use namespace

namespace  namespace name; ;
함수
namespace  namespace name; ;
함수

So let's do it.

<?php
    namespace hello;

    function hello()
    {
        return 'First hello function.';
    }

    namespace hello2;

    function hello()
    {
        return 'Second hello function.';
    }
?>

Running the above code will not throw any errors. ^^
The first hello function belongs to the hello group, and the second hello function belongs to the hello2 group.
Now let's look at how to call a function in your code using namespaces.

How to Call a Function Using namespace

\namesapce\functionname()

So let's look at an example.

<?php
    namespace hello;

    function hello()
    {
        return 'First hello function.';
    }

    namespace hello2;

    function hello()
    {
        return 'Second hello function.';
    }

    echo \hello\hello();
    echo '<br>';
    echo \hello2\hello();
?>

So we learned about namespaces.
Namespaces also allow you to declare the same class name as the same function.
Same.

How to Create Instance Using a namespace

$variable = new \namespace name\class name
<?php
    namespace hello;

    class hello
    {
        function hello()
        {
            return 'First hello function.';
        }
    }


    namespace hello2;

    class hello
    {
        function hello()
        {
            return 'Second hello function.';
        }
    }


    $helloFirst = new \hello\hello;
    echo $helloFirst->hello();
    echo '<br>';
    $helloSecond = new \hello2\hello;
    echo $helloSecond->hello();
?>

Result of the code above

Too long to use a namespace once?
You can use it as short phrase as you want.
See you next time.


Thank you for visiting. If you have any inquiry or explanation of mistakes, please use the comments below.


    
    

Back to the course

ALL COMMENTS 0

Sort by