child classes needing to define constant or set property

Not for 'how-to' coding questions but PHP theory instead, this forum is here for those of us who wish to learn about design aspects of programming with PHP.

Moderator: General Moderators

Post Reply
koen.h
Forum Contributor
Posts: 268
Joined: Sat May 03, 2008 8:43 am

child classes needing to define constant or set property

Post 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?
gregor171
Forum Newbie
Posts: 22
Joined: Thu Apr 16, 2009 5:09 pm
Location: Ljubljana, Slovenia

Re: child classes needing to define constant or set property

Post 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;
}
}
 
gregor171
Forum Newbie
Posts: 22
Joined: Thu Apr 16, 2009 5:09 pm
Location: Ljubljana, Slovenia

Re: child classes needing to define constant or set property

Post 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]
 }
 
Post Reply