0

Im trying to access a variable from one class through another class from a php script:

My first class is:

class data{

  private $length;
  private $height;      

   public function setLength($length){
    $this->length = $length;
   }

   public function getLength(){
    return $this->length;
   }

  public function setHeight($height){
    $this->height = $height;
   }

   public function getHeight(){
    return $this->height;
   }

}

I have another class:

class proccess extends data{

   public function getOrientation(){
      if($this->getLength() > $this->getHeight()) {
       $orientation = 'landscape';
      } else {
      $orientation = 'portrait';
   }

   }

}

When trying to access $this->getLenght() or $this-getHeight() from class process the values are empty; I am setting the values through my php script as so:

<?php


  require_once('functions/data.php');
  require_once('functions/process.php');

  $data=new data();
  $process = new process();

  $data->setLength(25);
  $data->setHeight(30);
  $orientation = $process->getOrientation();

Any ideas on why the function getOrientation is not able to get the value of width and length and how i can fix this?

Yeak
  • 2,470
  • 9
  • 45
  • 71

2 Answers2

3

You are setting values for a different object which is $data. You have to set them for $process.

  $process = new process();

  $process->setLength(25);
  $process->setHeight(30);
  $orientation = $process->getOrientation();
MahanGM
  • 2,352
  • 5
  • 32
  • 45
-1

The variables should be protected not private - see these:

http://php.net/manual/en/language.oop5.visibility.php What is the difference between public, private, and protected?

And, as pointed out by MahanGM, you are using two different instances of objects, that aren't related to each other at all. You should either be doing $process->setLength and $process->setHeight or $data->getOrientation.

Community
  • 1
  • 1
Nathan Loding
  • 3,185
  • 2
  • 37
  • 43
  • 2
    Do they need to be protected? `process` only uses the public methods of `data` in the example, so it wouldn't need to be able to access `$length` or `$height` directly. – Clart Tent Oct 28 '13 at 21:08
  • No, as long as the properties are always accessed through the getters and setters `setFoo()` and `getFoo()` the variables should stay `private` – Coded Monkey Oct 28 '13 at 21:13