简体   繁体   中英

Extends a PHP class and it's children

In one of my projects, I use an external library providing two classes : DrawingImage and DrawingCharset , both of them extending BaseDrawing .

I want to extends BaseDrawing to add some properties and alter an existsing method. But I also want theses modifications in "copy" of existing children ( DrawingImage and DrawingCharset ).

There is a simple way to do it ? Extending don't seems to be a solution : I must duplicate code between each subclass. And I'm not sure i can call a parent method through Trait.

Traits can access properties and methods of superclasses just like the subclasses that import them, so you can definitely add new functionality across children of BaseDrawing with traits.

<?php
class BaseDrawing
{
    public $baseProp;

    public function __construct($baseProp)
    {
        $this->baseProp = $baseProp;
    }

    public function doSomething()
    {
        echo 'BaseDrawing: '.$this->baseProp.PHP_EOL;
    }
}

class DrawingImage extends BaseDrawing
{
    public $drawingProp;

    public function __construct($baseProp, $drawingProp)
    {
        parent::__construct($baseProp);
        $this->drawingProp = $drawingProp;
    }

    public function doSomething()
    {
        echo 'DrawingImage: '.$this->baseProp.' - '.$this->drawingProp.PHP_EOL;
    }
}

class DrawingCharset extends BaseDrawing
{
    public $charsetProp;

    public function __construct($baseProp, $charsetProp)
    {
        parent::__construct($baseProp);
        $this->charsetProp = $charsetProp;
    }

    public function doSomething()
    {
        echo 'DrawingCharset: '.$this->baseProp.' - '.$this->charsetProp.PHP_EOL;
    }
}

/**
 * Trait BaseDrawingEnhancements
 * Adds new functionality to BaseDrawing classes
 */
trait BaseDrawingEnhancements
{
    public $traitProp;

    public function setTraitProp($traitProp)
    {
        $this->traitProp = $traitProp;
    }

    public function doNewThing()
    {
        echo 'BaseDrawingEnhancements: '.$this->baseProp.' - '.$this->traitProp.PHP_EOL;
    }
}

class MyDrawingImageImpl extends DrawingImage
{
    // Add the trait to our subclass
    use BaseDrawingEnhancements;
}

class MyDrawingCharsetImpl extends DrawingCharset
{
    // Add the trait to our subclass
    use BaseDrawingEnhancements;
}

$myDrawingImageImpl = new MyDrawingImageImpl('Foo', 'Bar');
$myDrawingImageImpl->setTraitProp('Wombats');

$myDrawingCharsetImpl = new MyDrawingCharsetImpl('Bob', 'Alice');
$myDrawingCharsetImpl->setTraitProp('Koalas');

$myDrawingImageImpl->doSomething();
$myDrawingCharsetImpl->doSomething();

$myDrawingImageImpl->doNewThing();
$myDrawingCharsetImpl->doNewThing();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM