Page 1 of 1
child classes needing to define constant or set property
Posted: Fri Apr 17, 2009 2:09 pm
by koen.h
The interface has a getter method. And abstract method implements this interface using 'return $this->property' in this method. How can I enforce classes that extend this to have this property set?
Currently I've come up with this:
Code: Select all
interface A {
public function getValue();
}
abstract class B implements A {
protected $value;
public function getValue() {
if (!isset($this->value)) { throw new Exception('message'); }
return $this->property;
}
}
Other ideas?
Re: child classes needing to define constant or set property
Posted: Tue Apr 21, 2009 10:28 am
by gregor171
I think you are asking for this
Code: Select all
interface A {
public function getValue();
public function setValue($value);
}
then there are a few ways to do this. this is one:
Code: Select all
abstract class B {
// no implement here
protected $value;
public function getValue() {
if (!isset($this->value)) { throw new Exception('message'); }
return $this->property;
}
}
class C extends B implements A{
public function setValue($value){
$this->value= $value;
}
}
Re: child classes needing to define constant or set property
Posted: Tue Apr 21, 2009 10:53 am
by gregor171
Ups. Sorry for that one. It should nearly work, but. An abstract class should contain at least one abstract method. Mine doesn't as well as yours. So delete abstraction in first sample and it should work.
Interface that I made is ok.
But there is a second easy way:
Code: Select all
abstract class B implements A {
protected $value;
public function getValue() {
if (!isset($this->value)) { throw new Exception('message'); }
return $this->property;
}
// this will enforce implementation of method in classes that extend B
[color=#4000BF]abstract public function setValue($value);[/color]
}