Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Fatal error: Interface not found, using factory pattern 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 - Runs fine.

php FactoryPattern/FactoryClassPattern/User.php - gives following errors: PHP Fatal error: Interface 'DesignPatternsWithPhpLanguage\FactoryPattern\FactoryClassPattern\UserInterface' not found in /Users/jitendraojha/www/DesignPatternsWithPhpLanguage/FactoryPattern/FactoryClassPattern/User.php on line 7

I had use UserInterface; added in File 2 with no solution.

like image 351
jitendra Avatar asked Sep 19 '15 16:09

jitendra


1 Answers

All you need its include, but better yet you should use an autoloader

See example below for quick test with include, assumption here is 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();
like image 164
jasonlam604 Avatar answered Nov 14 '22 21:11

jasonlam604