PHP: How to instantiate a class from a property 'className' - php

Imagine this code:
class MyClass
{
private string $className;
public function __construct(string $className)
{
$this->className = $className;
}
public function instantiateClass()
{
$className = $this->className;
return new $className();
}
}
Is there a way to instantiate the class without first assigning the property value to the local variable $className in method instantiateClass()?
Something like this:
class MyClass
{
private string $className;
public function __construct(string $className)
{
$this->className = $className;
}
public function instantiateClass()
{
// This cannot be done as 'className' should be a method, not the property
return new $this->className();
}
}
Any ideas?

So, as pointed out by #Cid in the comments below my question, the solution is actually the one I thought was wrong:
class MyClass
{
private string $className;
public function __construct(string $className)
{
$this->className = $className;
}
public function instantiateClass()
{
// This works! It doesn't find a method, but reads the property correctly!
return new $this->className();
}
}

you can use __CLASS__ or self:: or static::
you can try
class MyClass
{
public function __construct()
{
}
static public function instantiateClass()
{
return new self();
}
static public function instantiateClassWithStatic()
{
return new static();
}
}
$myInstance = MyClass::instantiateClass();

Related

why is php class not being loaded

Im testing this thing where i'm trying to load a class and use it like this:
$this->model->model_name->model_method();
This is what I've got:
<?php
error_reporting(E_ALL);
class Loader {
public function model($model)
{
require_once("models/" . $model . ".php");
return $this->model->$model = new $model;
}
}
class A {
public $load;
public $model;
public $text;
public function __construct()
{
$this->load = new Loader();
$this->load->model('Test');
$this->text = $this->model->Test->test_model();
}
public function get_text()
{
return $this->text;
}
}
$text = new A();
echo $text->get_text();
?>
Im getting a bunch of errors here:
Warning: Creating default object from empty value in
C:\xampp\htdocs\fw\A.class.php on line 9
Notice: Trying to get property of non-object in
C:\xampp\htdocs\fw\A.class.php on line 24
Fatal error: Call to a member function test_model() on a non-object in
C:\xampp\htdocs\fw\A.class.php on line 24
What am I doing wrong? Thanks for any tip!
P.S. not much in the loaded file:
<?php
class Test {
public function test_model()
{
return 'testmodel';
}
}
?>
In the A class' constructor you are not assigning the "loaded" model to anything and later you are trying to use the $model property which has nothing assigned to it.
Try this:
class A {
public $load;
public $model;
public $text;
public function __construct()
{
$this->load = new Loader();
$this->model = $this->load->model('Test');
$this->text = $this->model->test_model();
}
(...)
Problem may be that you have not defined Loader.model as object but treating it like it is.
class Loader {
public $model = new stdClass();
public function model($model)
{
require_once("models/" . $model . ".php");
return $this->model->$model = new $model();
}
}
When you have your class like this you can use
$this->model->model_name->model_method();
Try the following code(UPDATED) if you want to avoid $this->model = $this->load->model('Test') in the constructor.
You can simply load the models by calling $this->loadModel(MODEL) function
<?php
error_reporting(E_ALL);
class Loader {
private $models = null;
public function model($model)
{
require_once("models/" . $model . ".php");
if(is_null($this->models)){
$this->models = new stdClass();
}
$this->models->$model = new $model();
return $this->models;
}
}
class A{
public $load;
public $model;
public $text;
public function __construct()
{
$this->load = new Loader();
$this->loadModel('Test');
$this->loadModel('Test2');
$this->text = $this->model->Test2->test_model();
}
public function get_text()
{
return $this->text;
}
private function loadModel($class){
$this->model = $this->load->model($class);
}
}
$text = new A();
echo $text->get_text();
?>

PHP simple chain class methods without create object

in this below class i want to use class like with static methods and for use class methods without create new object from parent.
for example:
<?php
class Permission
{
protected $permission = false;
protected $id = 0;
public static function __construct()
{
return new static;
}
public function user( $id )
{
$this->id = $id;
}
public function check()
{
$this->permission = true;
}
public function item( $item )
{
return $item;
}
}
$bar = Permission::user(100)->item("HELLO");
print_r($bar);
this code not working and have problem. how to resolve this class problem?
That will not work because user method is not static, try changing this two methods, and this is good way of generating objects
public function __construct($id)
{
$this->id = $id;
}
public static function user( $id )
{
return new static($id);
}
I'd suggest you a singleton pattern, like this
class Permission
{
static protected $permission = false;
static protected $id = 0;
private static $_instance = null;
private function __construct () { }
public static function getInstance()
{
if (self::$_instance === null) {
self::$_instance = new self;
}
return self::$_instance;
}
public static function user( $userId )
{
self::$id = $userId;
return self::$_instance;
}
public static function check()
{
self::$permission = true;
return self::$_instance;
}
public static function item( $item )
{
return $item;
}
}
$bar = Permission::getInstance()->user(100)->item("HELLO");
print_r($bar);
You can chain methods in 'dynamic' classes by returning $this at the end of method (remember, you have a static).
class A {
public function someMethod()
{
// some code
return $this
}
public function otherMethod()
{
// some code
return $this
}
$a = new A();
$a->someMethod()->otherMethod();
}

Calling inherited method form base class

I have an extended class with an overriden method doSomething().
For some reason the inherited class' method never runs only the base one.
class cDemoClass {
public static function getInstance() {
static $instance = null;
if ($instance === null)
$instance = new cDemoClass();
return $instance;
}
private function __construct() {
}
protected function doSomething() {
echo 'do something';
}
public function call_me() {
$this->doSomething();
}
}
class cDemoClassEx extends cDemoClass {
protected function doSomething() {
echo 'do something differently';
}
}
$baseclass = cDemoClass::getInstance();
$baseclass->call_me();
echo '<br/>';
$extendedclass = cDemoClassEx::getInstance();
$extendedclass->call_me();
result:
do something
do something
The second one should be "do something differently" at least that's what I'm expecting.
Can anyone tell me what I'm doing wrong? Thanks
In this case, you need using late static binding (5.3+). Change in parent method getInstance line :
$instance = new cDemoClass();
to
$instance = new static();
You will get:
do something
do something differently
Read more about this feature here: http://www.php.net/manual/en/language.oop5.late-static-bindings.php
Because cDemoClassEx::getInstance(); is still returning new cDemoClass();. You have to also overwrite the getInstance() method:
class cDemoClass {
public static function getInstance() {
static $instance = null;
if ($instance === null)
$instance = new cDemoClass();
return $instance;
}
private function __construct() {
}
protected function doSomething() {
echo 'do something';
}
public function call_me() {
$this->doSomething();
}
}
class cDemoClassEx extends cDemoClass {
public static function getInstance() {
static $instance = null;
if ($instance === null)
$instance = new cDemoClassEx();
return $instance;
}
private function __construct() {
}
protected function doSomething() {
echo 'do something differently';
}
}
$baseclass = cDemoClass::getInstance();
$baseclass->call_me();
echo '<br/>';
$extendedclass = cDemoClassEx::getInstance();
$extendedclass->call_me();
You have to override with the cDemoClassEx::getInstance() and change this line
$instance = new cDemoClass();
into
$instance = new cDemoClassEx();
You will also need to declare the cDemoClass::__construct() as protected or simply override it in cDemoClassEx.

PHP : Function argument must be an Object with dynamic class name

so I am new in the world of object oriented programming and I am currently facing this problem (everything is described in the code):
<?php
class MyClass {
// Nothing important here
}
class MyAnotherClass {
protected $className;
public function __construct($className){
$this->className = $className;
}
public function problematicFunction({$this->className} $object){
// So, here I obligatorily want an $object of
// dynamic type/class "$this->className"
// but it don't works like this...
}
}
$object = new MyClass;
$another_object = new MyAnotherClass('MyClass');
$another_object->problematicFunction($object);
?>
Can anyone help me ?
Thanks, Maxime (from France : sorry for my english)
What you need is
public function problematicFunction($object) {
if ($object instanceof $this->className) {
// Do your stuff
} else {
throw new InvalidArgumentException("YOur error Message");
}
}
Try like this
class MyClass {
// Nothing important here
public function test(){
echo 'Test MyClass';
}
}
class MyAnotherClass {
protected $className;
public function __construct($className){
$this->className = $className;
}
public function problematicFunction($object){
if($object instanceof $this->className)
{
$object->test();
}
}
}
$object = new MyClass;
$another_object = new MyAnotherClass('MyClass');
$another_object->problematicFunction($object);
That's called type hinting and what you want to do is just not supported.
If all those dynamic class names have something in common (e.g., they're different implementations for certain feature) you probably want to define a base (maybe abstract) class or an interface and use that common ancestor as type hint:
<?php
interface iDatabase{
public function __contruct($url, $username, $password);
public function execute($sql, $params);
public function close();
}
class MyClass implements iDatabase{
public function __contruct($url, $username, $password){
}
public function execute($sql, $params){
}
public function close(){
}
}
class MyAnotherClass {
protected $className;
public function __construct($className){
$this->className = $className;
}
public function problematicFunction(iDatabase $object){
}
}
Otherwise, just move the check to within problematicFunction() body, as other answers explain.

Singleton initialization configuration

There is a public library, and there is a class that can have only one instance in one PHP process, so it's Singleton. The problem is that initialization of this class require some configuration arguments and I can't find good issue to pass them in class constructor.
The only issue I found is:
public static function init($params) {
if(self::$instance) {
throw new Exception(__CLASS__ . ' already initialized');
}
$class = __CLASS__;
self::$instance = new $class($params);
}
public static function getInstance() {
if(!self::$instance) {
throw new Exception(__CLASS__ . ' is not initialized');
}
return self::$instance;
}
But I don't think that it's so really good.Is there any other ideas?
Thanks!
There is example of bad, but working issue:
if(!defined('PSEOUDSINGLETON_PARAM')) {
define('PSEOUDSINGLETON_PARAM', 'default value');
}
class PseoudoSingleton {
protected function __construct($param1 = PSEOUDSINGLETON_PARAM) {
// ...
}
public static function getInstance() {
if(!self::$instance) {
$class = __CLASS__;
self::$instance = new $class();
}
return self::$instance;
}
}
/* on library/utility level */
class nonSingletonService { public function __construct($options){} }
/* on application logic level, so, knows all context */
function getSingleton(){
static $inst;
if (!$inst) $inst=new nonSingletonService(calculateParameters());
return $inst;
}
Sample Singleton implementation:
class MySingleton
{
private static $_INSTANCE = null;
private function __construct()
{
// put initialization code here
}
public static function getInstance()
{
if(self::$_INSTANCE === null) self::$_INSTANCE = new MySingleton();
return self::$_INSTANCE;
}
}
Note that constructor is private, so it can only be called from the class itself.
References to the instance can be only obtained by getInstance call, which creates the object on first call, any subsequent calls will return references to an existing object.
Why are you checking it twice?
Just do the following:
private static function init($params) {
$class = __CLASS__;
self::$instance = new $class($params);
}
public static function getInstance($params) {
if(!self::$instance) {
self::init($params);
}
return self::$instance;
}
That way, you know that you only need to check once and you know you only call init() if the instance is not initialized.

Categories