Created
April 26, 2018 11:04
-
-
Save behkod/bd87818e3764d18ed4fc7a9e33940e66 to your computer and use it in GitHub Desktop.
Dynamic class loading in namespaced PHP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* File Component/Package/Vehicle/BicycleModel.php */ | |
namespace Component\Package\Vehicle; | |
class BicycleModel{ | |
//@ToDo: implement BicycleModel | |
} | |
?> | |
---------------------------------------------------------- | |
<?php | |
/* File Component/Package/Vehicle/CarModel.php */ | |
namespace Component\Package\Vehicle; | |
class CarModel{ | |
//@ToDo: implement CarModel | |
} | |
?> | |
----------------------------------------------------------- | |
<?php | |
/* File Component/Package/Vehicle/VehicleFactory.php */ | |
namespace Component\Package\Vehicle; | |
class VehicleFactory | |
{ | |
private $vehicleName; | |
public function __construct($vehicle = 'Bicycle'){ | |
$this->$vehicleName = $vehicle; | |
} | |
public function getInstance(){ | |
$className = $this->$vehicleName . 'Model'; | |
return new $className(); //This will return \BicycleModel & NOT \Component\Package\Vehicle\BicycleModel | |
/* This means it won't work as expected. We thought it will return a BicycleModel in the same namespace | |
* that is defined, But it didn't happen. Continue reading to see why */ | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment