PHP Fatal error: interface not found using factory template with namespaces

File 1 - /Users/jitendraojha/www/DesignPatternsWithPhpLanguage/FactoryPattern/FactoryClassPattern/UserInterface.php

<?php

namespace DesignPatternsWithPhpLanguage\FactoryPattern\FactoryClassPattern;

interface UserInterface
{

    function setFirstName($firstName);
    function getFirstName();
}

?>

File 2 - /Users/jitendraojha/www/DesignPatternsWithPhpLanguage/FactoryPattern/FactoryClassPattern/User.php

<?php

namespace DesignPatternsWithPhpLanguage\FactoryPattern\FactoryClassPattern;


class User implements UserInterface
{

    private $firstName = null;

    public function __construct($params) {   }

    public function setFirstName($firstName)
    {

        $this->firstName = $firstName;
    }

    public function getFirstName()
    {

        return $this->firstName;
    }
}

?>

Problem

php FactoryPattern/FactoryClassPattern/UserInterface.php - works fine.

php FactoryPattern/FactoryClassPattern/User.php - gives the following errors: PHP Fatal error: the interface 'DesignPatternsWithPhpLanguage \ FactoryPattern \ FactoryClassPattern \ UserInterface' was not found in /Users/jitendraojha/www/DesignPatternsWithPhpLanguage/FactoryPattern/FactoryClassPattern/User/Unit

I added use UserInterface;to file 2 without a solution.

+4
source share
1 answer

All you need to do is enable it, but it's better to use the autoloader

See the example below for a quick test with inclusion, it is assumed that both files are in the same directory.

namespace DesignPatternsWithPhpLanguage\FactoryPattern\FactoryClassPattern;

include('UserInterface.php');

class User implements UserInterface
{

    private $firstName = null;

    public function __construct($params) {   }

    public function setFirstName($firstName)
    {

       $this->firstName = $firstName;
    }

    public function getFirstName()
    {

       return $this->firstName;
     }

}

// Quick test will - output ===> John
$user = new User(null);
$user->setFirstName('John');
echo $user->getFirstName();
+6

Source: https://habr.com/ru/post/1608154/


All Articles