Skip to content

Instantly share code, notes, and snippets.

@behkod
Created April 26, 2018 11:04
Show Gist options
  • Save behkod/bd87818e3764d18ed4fc7a9e33940e66 to your computer and use it in GitHub Desktop.
Save behkod/bd87818e3764d18ed4fc7a9e33940e66 to your computer and use it in GitHub Desktop.
Dynamic class loading in namespaced PHP
<?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