Michael V
Michael V

Reputation: 59

Basic OOP PHP form class

I'm just experimenting with OOP programming I'm trying to create a form class. I'm unable to print the checkbox, how can I check where things are going wronge?

  require_once('form.php');
  $gender = new Checkbox('Please select your gender','gender',array('male','female'));
  echo $gender->show_checkbox();

File with class:

class Inputfield{

  public $id;
  public $options_array;
  public $question;
  public $type;
  function __construct($newquestion,$newid,$newoptions_array){
    $this->question=$newquestion;
    $this->id=$newid;
    $this->type="txt";
    $this->options_array=$newoptions_array;
  }
  public function show_options($options_arr,$type,$id,$classes){
    $output="";
    foreach($options_arr as $option){
        $output.="<label for=\"".$option."\"></label><input name=\"".$option."\" type=\"".$type."\" id=\"".$id."\" class=\"".$classes."\">";
    }
    return $output;
  }
  public function show_question(){
    $output="<h3 class='question'>".$this->vraag."</h3>";
    return $output;
  }
}
class Checkbox extends Inputfield{
  function __construct($newquestion,$newid,$newoptions_array){
    $this->question=$newquestion;
    $this->id=$newid;
    $this->type="checkbox";
    $this->options_array=$newoptions_array;
  }

  public function show_checkbox(){
    $output=show_question();
    $output.=show_options($this->options_array,'checkbox',$this->id,'class');
    return $output;
  }
}

Upvotes: 0

Views: 807

Answers (2)

bummzack
bummzack

Reputation: 5875

You should use $this in an object context. Eg. in your show_checkbox method, write:

$output = $this->show_question();
$output .= $this->show_options(...);

Upvotes: 2

zerkms
zerkms

Reputation: 254944

  1. You call instance methods with $this: $this->show_options();
  2. You don't need to copy-paste the whole constructor as soon as it's identical to the one in parent class
    1. In case if it matches partially you can call it like parent::__construct(...) and then define a custom $this->type="checkbox";
    2. You can not define it in runtime but specify it as a property default value.

Upvotes: 5

Related Questions