Jump to content

cloning code problem


silverglade

Recommended Posts

Hi, I am trying to clone a car object and nothing outputs to the screen past "error negative gas..." Please any help greatly appreciated. thank you.

 

<html>
<body>
<?php

class Car
{
private $gas = 0;
private function addGas($amount)
{
	$this->gas = $this->gas + $amount;
	echo "<br />$amount gallons added to gas tank<br/>";
}
function buyGas($amount)
{
	$this->addGas($amount);
}
function negativeGas($amount)
{
	$this->gas = $this->gas - 5;
	  try
	  {
		if ($this->gas < 0)
		{
			throw new Exception ("Error, negative amount of gas.");
		}
	   }
	   catch (Exception $e)
	   {
			echo $e->getMessage();
			echo "\n<br/>\n";
			exit();
	   }
}

function __clone()
{
	$this->gas = 0;
	echo "<br/>hello I am a clone!<br/>";
}	
}


$new_car = new Car;
$new_car->buyGas(5);
$another_car = new Car;
$another_car->negativeGas(4);
$clone_car = clone $new_car;
$clone_car->negativeGas(4);
?>
</body>
</html>

Link to comment
https://forums.phpfreaks.com/topic/242488-cloning-code-problem/
Share on other sites

Thank you. I added  return $this to the code and got the same result, it didn't echo out the clone message. please any more advice would be great if you can. here is the changed full code. thanks.

 

<html>
<body>
<?php

class Car
{
private $gas = 0;
private function addGas($amount)
{
	$this->gas = $this->gas + $amount;
	echo "<br />$amount gallons added to gas tank<br/>";
}
function buyGas($amount)
{
	$this->addGas($amount);
}
function negativeGas($amount)
{
	$this->gas = $this->gas - 5;
	  try
	  {
		if ($this->gas < 0)
		{
			throw new Exception ("Error, negative amount of gas.");
		}
	   }
	   catch (Exception $e)
	   {
			echo $e->getMessage();
			echo "\n<br/>\n";
			exit();
	   }
}

function __clone()
{
	$this->gas = 0;
	echo "<br/>hello I am a clone!<br/>";
	return $this;
}	
}


$new_car = new Car;
$new_car->buyGas(5);
$another_car = new Car;
$another_car->negativeGas(4);
$clone_car = clone $new_car;
$clone_car->negativeGas(4);
?>
</body>
</html>

It is not getting cloned because the script will end execution at this line

$another_car->negativeGas(4);

 

There you get negative gas and throw exception and after that you call exit(); So the rest of the script (the cloning part) is not executed at all. It does not require the return $this; in the __clone() function to work.

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.