Dynamic class is expanding

Is there a way to define a class so that it extends another class only if that class is available?

+5
source share
5 answers

There is nothing that would allow you to do

class Foo extendsIfExist Bar

But you can monkeypatch foo with runkit

An example from the PHP manual:

class myParent {
  function parentFunc() {
    echo "Parent Function Output\n";
  }
}

class myChild {
}

runkit_class_adopt('myChild','myParent');
myChild::parentFunc();

The runkit extension is available in PECL. However, using this is not recommended , because it is almost always an indicator for erroneous design.


: , - - , . , .

, , , . -

interface Loggable
{
    public function log($message);
}
class Foo implements Loggable
{
    protected $logger;
    public function setLogger($logger)
    {
        $this->logger = $logger;
    }
    public function log($message)
    {
        if($this->logger !== NULL) {
            return $this->logger->log($message);
        }
    }
}

log(). , , , Foo, , , Loggable. Logger, Foo. , , . solid.

+8

.

if (class_exists('parentClass') {
  class _myClass extends parentClass {}
} else {
  class _myClass {}
}
class myClass extends _myClass
{
...
}
+4

.

-, Pekka, , eval ,

if(class_exists("bar"))
{
     class foo extends bar
     {

     }
}

.

+2

, ClassB ( ), A.

( , ):

namespace someNamespace;

spl_autoload_register(function($class) {
    if (strcasecmp($class, 'someNamespace\SomeFakeClass') === 0) {
        if (class_exists('ClassB',false)) {
            class_alias('ClassB', 'someNamespace\SomeFakeClass');
        } else {
            class_alias('ClassA', 'someNamespace\SomeFakeClass');
        }
    }
}, true, true);

/** @noinspection PhpUndefinedClassInspection */
/** @noinspection PhpUndefinedNamespaceInspection */
class MyClass extends \someNamespace\SomeFakeClass {
    # ... real logic here ...
}

, MyClass ClassB, , ClassA.

eval, .

, .

EDIT: Just a note, the @noinspection notation exists, so IDEs like PHPStorm will not report errors regarding a class that does not exist.

+2
source

Do you mean this?

<?php

class Foo{
}

if( class_exists('Foo') ){
    class SubFoo extends Foo{
    }
}

if( class_exists('Bar') ){
    class SubBar extends Bar{
    }
}

$a = new SubFoo; // OK
$b = new SubBar; // Fatal error: Class 'SubBar' not found
+1
source

All Articles