P
P
Pavel Logachev2015-03-19 21:22:40
PHP
Pavel Logachev, 2015-03-19 21:22:40

How to call overridden classes inside base class?

The situation is this: there are two base classes

<?php
namespace AppBase;

class App
{
    protected $loader;

    public function __construct()
    {
        $this->loader = new Loader();
    }
}

<?php
namespace AppBase;

class Loader {}

And there are inherited classes:
<?php
namespace AppExample;

class App extends \AppBase\App {}

<?php
namespace AppExample;

class Loader extends \AppBase\Loader {}

How, without overriding the \AppBase\App constructor, to make \AppExample\App::$loader create an instance of the class \AppExample\Loader , and not \AppBase\Loader ?
It is impossible to explicitly prescribe namespace in the base class - it is not known in advance. I see only two options:
1) a field with a string containing the full name of the class ( public $loaderClass = '\AppExample\Loader'; )
2) a function that returns a Loader object
In both cases, override which class is called in the \AppExample\App constructor It will be quite simple, but these solutions do not seem successful to me.
Another option is to define get_called_class(), clip NS, look for the Loader class in the clipped NS, and if it is not found, then call it from the current one.
Maybe there are more standard solutions to this issue?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
Y
Yuri, 2015-03-19
@error500

I don’t understand why you need such a decision, but you can still try this

namespace AppBase;
class App
{
    protected $loader;

    public function __construct()
    {
        	$reflectionClass = new \ReflectionClass($this);
    	    $namespace = $reflectionClass->getNamespaceName(); //AppExample
    	    echo $namespace;
       /*Логика*/
    }
    
}
namespace AppBase;
class Loader {}
namespace AppExample;
class App extends \AppBase\App {}
namespace AppExample;
class Loader extends \AppBase\Loader {}

$app = new \AppExample\App();

A
Alexey, 2015-03-20
@rdifb0

And if so

class App {
      protected $loader;
  
      public function __construct(ILoader $loader)
      {
          $this->loader = $loader;
      }
      
  }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question