Reputation: 1730
I have a class named Service_B
which extends a custom service class.
This custom service class requires one single object named Reader
in its __construct()
in order to instantiate properly.
The parent service is defined as follow
namespace Vendor\Services;
abstract class Service{
function __construct(Vendor\Services\Reader $reader){
}
}
Service_B
is defined as follow:
namespace Vendor\Services;
class Service_B extends Service{
function __construct(){
parent::__construct(new \Vendor\Services\Reader());
}
}
Reader
do have the following line at the top of the file:
use Vendor\Services;
Class files are organized like this:
Vendor/Services/Service_B.php
Vendor/Services/Reader.php
Question: When I instantiate Service_B, I get the following error message:
Fatal error: Class 'Vendor\Services\Reader' not found
I don't understand why I get this error since I think I am using the proper namespaces declarations. Thank you
Upvotes: 1
Views: 571
Reputation: 19285
On top of your Reader
class place:
//This will declare the Reader class in this namespace
namespace Vendor\Services;
and remove:
//THIS IS A WRONG DIRECTIVE: you're telling PHP to use the Vendor\Services class but it doesn't even exist
use Vendor\Services;
Then modify the Service_B
class as follow:
namespace Vendor\Services;
//i think this should extend Service, as it's calling the parent constructor
class Service_B extends Service
{
function __construct(){
parent::__construct( new Reader() );
}
}
This way all yours 3 classes will be in the same namespace, and the Reader
class should be found without explicit namespace prefix
Upvotes: 3