Anthony Posted September 7, 2015 Share Posted September 7, 2015 In the "Namespaces" section in Ch.6, Larry describes how the use keyword can allow us to reference a namespace once in our script so that we don't need to name the specific namespace over and over again when we make objects: PHP allows you to more quickly reference a namespace by bringing it into current scope via the use keyword:use MyNamespace\Company;Having done that, you can now create an object by just referencing classes within the Company namespace:$obj = new Department(); Unfortunately, I am getting a class not found error when I try to use this. See program below, a shorter version of the type hinting example used earlier in the book. Company.php <?php namespace MyNamespace\Company; class Department{ private $_name; private $_employees; function __construct($name){ $this->_name = $name; $this->_employees = array(); }//__construct function addEmployee(Employee $e){ $this->_employees[] = $e; echo "<p>{$e->getName()} has been added to the {$this->_name} department.</p>"; }//addEmployee }//Department class Employee{ private $_name; function __construct($name){ $this->_name = $name; } function getName(){ return $this->_name; }//getName }//Employee ?> Using use in a separate file in the same directory as Company.php: <?php require('Company.php'); use MyNamespace\Company; $hr = new Department("Human Resources"); $e1 = new Employee("mary"); $hr->addEmployee($e1); ?> The code above generates a fatal error: "Fatal error: Class 'Department' not found" Am I missing something or am I not using use properly? Any assistance is greatly appreciated. Link to comment Share on other sites More sharing options...
Anthony Posted September 7, 2015 Author Share Posted September 7, 2015 I ran into this thread after posting which answers my question: http://www.larryullman.com/forums/index.php?/topic/3267-ch-6-use-namespace-correction/ The classes used need to be specified: use MyNamespace\Company\Department; use MyNamespace\Company\Employee; Link to comment Share on other sites More sharing options...
Recommended Posts