Differences

This shows you the differences between two versions of the page.

Link to this comparison view

jf_oop_1 [2017-09-01 14:54]
jf_oop_1 [2022-07-18 13:20] (current)
Line 1: Line 1:
 +====== Koden från genomgång nr1 på OOP ======
 +<code php>
 +<?php
 +/**
 + * Exempel på en enkel klass
 + * Första lektion på Prog C
 + */
  
 +class Animal {
 +  protected  $weight;
 +  private $legs;
 +  
 +  function __construct($weight=0){
 +    $this->weight = $weight;
 +  }
 +  
 +  public function getWeight() { // public är default
 +    return 'Djuret har vikten :' . $this->weight . '<br>';
 +  }
 +  
 +  function setWeight($weight) {
 +    $this->weight = $weight;
 +  }
 +
 +  public function getLegs() { // public är default
 +  return $this->legs;
 +  }
 +  
 +  function setLegs($legs) {
 +  $this->legs = $legs;
 +  }
 +  
 +  function info() {
 +    echo 'Vikt: ' . $this->getWeight() . '<br>Ben: ' . $this->getLegs() . '<br>'; 
 +  }
 +}
 +
 +class Dog extends Animal {
 +  
 +  function test() {
 +    return $this->weight;
 +  }
 +  
 +  function getWeight(){
 +    return 'Hunden har vikten: ' . $this->weight . '<br>';
 +  }
 +  
 +  function getLegs() {
 +    return 'Dog: ' . parent::getLegs();
 +  }
 +
 +}
 +
 +
 +include('head.php');
 +
 +$a2 = new Animal(23);
 +$a2->setLegs(2);
 +echo $a2->getWeight();
 +echo 'a2:' . $a2->getLegs() . '<br>';
 +
 +$d1 = new Dog(18);
 +$d1->setLegs(4);
 +echo 'd1: ' . $d1->getLegs() . '<br>';
 +echo $d1->getWeight();
 +echo $d1->info();  // Det kan vara bra att fatta vad som händer här...
 +
 +include('foot.php');
 +
 +</code>