Jump to content

[SOLVED] returning mulitple variables from a function


Recommended Posts

Not sure if this matters but my function is actually part of a class.  I am just trying to return 2 variables, from what I have read I need to store these variables in an array, but I can't seem to get the data out.  Here is my code for the class:

 

class Dragon {

private $dragonhitpoints;
private $attackname;

/////////////////////////////////////////////////////////
// constructor
/////////////////////////////////////////////////////////	

public function __construct($action){
	if($action == 'sword'){
		$this->dragonhitpoints = $this->firespit();
		$this->attackname = 'firespit';

		return array($this->dragonhitpoints, $this->attackname);

	}
	elseif ($action == 'arrow'){
		return $this->dragonhitpoints = $this->swoopdive();
		return $this->attackname = 'swoopdive';
	}
}

/////////////////////////////////////////////////////////
// public functions
/////////////////////////////////////////////////////////

// FireSpit - If hero attacks with sword dragon attacks with firespit 1-21 hitpoints
public function FireSpit(){
	return $this->dragonhitpoints = rand(1,21);
	//return $this->attackname = 'firespit';
}

// SwoopDive - If hero attacks with arrow dragon attacks with swoopdive 6-12 hitpoints
public function SwoopDive(){
	$this->dragonhitpoints = rand(6,12);
	//$this->attackname = 'swoop dive';
}

}

?>

 

and here is the code I am using to call the class and list the array:

 

$DragonAct = new Dragon($action);

list ($dragonattack, $dragonhitpoints) = $DragonAct->__construct($action);

Try doing just $a = $DragonAct->__construct($action); and then var_dump($a);.  That lets you inspect the return value before trying to assign it with list().

 

Your code looks ok when action is sword, but not ok when action is arrow.

 

As a side note, it seems odd to me to have code like that in a constructor, if the object represents a Dragon.

Yes I know certain parts aren't going to work.  I've been moving more and more of the code to be OOP so some stuff looks funky right now.  Sorry I don't think I fully understand the use of the construct function. Perhaps you can enlighten me on that matter?

var_dump gives me the following output:

 

array(2) { [0]=>  int(5) [1]=>  string( "firespit" }

 

After removing the __construct() from the class and flipping the order of the values in the array everything seems to be working.  I guess I'll need to read more to understand the proper use of the construct.

A construct is used to setup properties within an instance of an object. An example.

 

<?php

  class foo {
    
    private $msg;
    
    function __construct($s) {
      $this->msg = $s;
    }
    
    function hello() {
      return "hello " . $this->msg;
    }
  }

  $foo = new foo('thorpe');
  $foo->hello();

?>

 

It can be used to setup allot more obviously, db connections and the like, but thats just a simple example.

As a simple example, let's say your class represents a rectangle.

It would have the properties [i]length[/i] and [i]width[/i].  It would also likely have the methods [i]getArea()[/i], [i]setWidth()[/i], and [i]setHeight()[/i].

In order to understand why a constructor is useful you have to understand languages other than PHP.  In PHP, you don't have to declare or initialize variables.  It's considered [i]bad programming practice[/i] to do so, but you can almost always count on PHP to initialize your variables to empty or zero.  As an example, if $var is undeclared and you do:
[code]
$var += 5;

$var will then hold the value 5.  This is because PHP will declare and initialize your variable for you.

 

Now let's look at a typed language such as C++.  In C++ you must declare your variables and you should initialize them as well.  In order to understand why this is the case, you have to understand how variables work.  When you create a variable in a program, your interpreter or compiler grabs a chunk of memory out of the available memory in the computer.  That memory that is grabbed is available now for your program, but it may not have been available 2 minutes ago; 2 minutes ago it may have been in use by another program and that program may have left a value in that memory.

 

So in a language such as C++, when you declare a variable:

  int my_num;

 

There is no way for you to predict what value that variable holds.  It could be 5, it could be 10, it could be -32,322.  You can not safely use this variable in any calculations.  The following code will most likely crash your program in C++:

int compute( int param ){
  int my_num; // UNINTIALIZED!!!
  return param * my_num;  // UNPREDICTABLE RESULT
}

 

Going back to our rectangle class:

class Rectangle{
  var $length, width;

  // Not defining a constructor!

  function setWidth($val){
    $this->width = $val;
  }

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

  function getArea(){
    return $this->length * $this->width;
  }
}

 

When you create an instance of this class in PHP, the rectangle's width and height will most likely be set to zero for you.  Calling getArea() on this instance would return 0 as well, which is fairly safe (but still bad programming practice because you are relying on the interpreter to perform steps for you).

 

If someone in C++ creates an instance of that class and then calls getArea(), there is no telling what value they will get back.  The length and width properties have not been set, so the return value of getArea is unpredictable.

 

Enter the constructor:

  function __constructor(){
    $this->length = 0;
    $this->width = 0;
  }

 

Now it is guaranteed that if someone in C++ creates an instance of Rectangle without specifying a width and length that when they call getArea they will get a predictable result.  This is a necessary requirement for them to write a program that uses this class.

 

Hope that helps.

 

P.S. Yes, I'm aware of the syntax differences between a class in PHP and C++; I kept it simple on purpose.

 

P.P.S.  Always provide a constructor and always initialize your variables before using them, in any language, and regardless of whether the compiler will initialize them for you.  You never know when your code will be moved to an installation or platform that doesn't initialize them or uses a different initialization value, so provide one yourself.[/code]

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.