Jump to content

Function that returns several values, how to OOP call it ?


Dzherzinsky

Recommended Posts

:confused:

 

 

Hello

 

 

I just copied and pasted what you wrote, here is a full copy of paste of the files in question. I agree with you that your code made perfect sense, so I dont know where I am screwing up  :confused:

 

<?php


class Motorbike extends Vehicle {

protected $bikes_speed = array();


   /*public function speed ($d1, $d2, $d3)
   {
      // the 'this' keyword denotes that the variable $bikes_speed belongs to the current object
      $this->bikes_speed[] = $d1/10;
      $this->bikes_speed[] = $d2/10;
      $this->bikes_speed[] = $d3/10;

      return $this->bikes_speed;
   }*/



public function speed($speeds)
{
   foreach($speeds as $speed)
   {
      $this->bikes_speed[] = $speed/10;
   }

   return $this->bikes_speed;
}


}	


?>

 

and this is the other file

 


<?php



require_once 'vehicle.php';
require_once 'Motorbike.php';


$v1 = 50;
$v2 = 20;
$v3 = 600;

$suzuki = new Motorbike();
$speeds = $suzuki->speed($v1, $v2, $v3);

echo "Speeds are: ";

foreach($speeds as $speed)
{
   echo $speed . "<br />";
}

?>


 

The problem is that you're not passing an array into your object.  In your script, you need:

 

$v = array(50, 20, 600);

$suzuki = new Motorbike();
$speeds = $suzuki->speed($v);

echo "Speeds are: ";

foreach($speeds as $speed)
{
   echo $speed . "<br />";
}

 

Remember: a class is merely a blueprint, much like a function definition.  It doesn't become real until you instantiate it (create an object of your class' type) by calling "new classname();"  Just because you define a method (class function) to take an array as a parameter, that doesn't mean it magically happens.  You still need to construct the array and pass it into the method in the script yourself.

 

 

alright, so having the 3 arguments and sending them to an array does not work like when you assign the items to an array like

 

$my_array = array(1, 2, 3);

 

I thought that it would have been the same, gosh, sorry for so much inconvenience. I promise to watch more the forum and ask less.

 

I have learned a lot from you

 

best regards

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.