Almost final methods in PHP?

I have two abstract classes in the inheritance chain, within which there will eventually be a shared library:

abstract class Foo {
    public function baz() {
        echo 'Foo::baz()';
    }

    // other methods here
}

abstract class Bar extends Foo {
    public function baz() {
        echo 'Bar::baz()';
    }
}

These two classes should be extended by developers, and my problem is that I would like to make sure that none of the methods baz()can be overridden (since they contain strict RFC-compatible code). Creation is Bar::baz() finalnot a problem; however, if I do Foo::baz() final, then myself Bartoo cannot override it.

PHP 5.4 trait, , , PHP < 5.4 . - , , - , .

- , , , DRY (, )?

+5
3

, "" ". , .

interface Bazr {
    public function baz();

    public function myOtherMethod1();
    public function myOtherMethod2();
}

public class Foo implements Bazr {
  public final function baz() {} 
  public function myOtherMethod1() {/* default implementation of some method */}
  public function myOtherMethod2() {/* yeah */}
}

public class Bar implements Bazr {
  private parentBazr = null;
  public function __construct() {
    $this->parentBazr = new Foo();
  }

  public final function baz() {}
  public function myOtherMethod1() {
    $this->parentBazr->myOtherMethod1();
  }
  public function myOtherMethod2() {
    $this->parentBazr->myOtherMethod1();
  }
}

Foo Bar , Bar "" Foo, bas Foo, Bar. , ... PHP , , , , , . , ( ).

, java/php, , "$".

+1

, . , , , .

abstract class Foo {
private $bazBehaviour;
    public function __construct($bazBehaviour){
        $this->bazBehaviour=!empty($bazBehaviour)?$bazBehaviour:"defaultBazBehaviour";
    }
   final public function baz() {
       $this->bazBehaviour();
   }
   final protected function defaultBazBehaviour(){
        echo "Foo::Baz()";
    }
   // other methods here
}

abstract class Bar extends Foo {
    public function __construct(){
       parent::__construct("bazBehaviour");
    }
    final protected function bazBehaviour() {
        echo 'Bar::baz()';
     } 
}
class toto extends Bar{
     public function __construct(){
       parent::__construct();
    }
}
$d = new toto();
$d->baz();

PHP 5.3.13 : Bar:: ()

+2

, :

my problem is that I'd like to make it so that neither implementation of 
the baz() method can be overridden

However you redefine Foo:baz()in Bar.. so there are some fundamental design / requirements issues here.

0
source

All Articles