Page 1 of 1

Cloning an object when a function returns an array

Posted: Tue Nov 10, 2009 12:17 pm
by abhiuppu
Hi, I am a newbie to PHP and have been playing around with what I have been learning. I came across the concept of cloning and so I did try a sample example. For some reason, it does not seem to work. Here is the code I wrote:

<?php
class clone_obj
{
private $std_name;
private $std_id;

public function set_std_name($name)
{
$this->std_name=$name;
}
public function set_std_id($id)
{
$this->std_id=$id;
}
public function get_std_details()
{
$this->std[]=$this->std_name;
$this->std[]=$this->std_id;
return $this->std;
}

function __clone()
{ //echo "Cloning in progress<br/>";
$this->std_id="00";
echo "<br/>";
}

}

$std1=new clone_obj;

$std1->set_std_name("Abhishek");
$std1->set_std_id("01");
list($std_name,$std_id)=$std1->get_std_details();
echo $std_name."<br/>";
echo $std_id."<br/>";

$std2 = clone $std1;
$std2->set_std_name("Abhinay");
//$std2->set_std_id("00");
list($std_name,$std_id)=$std2->get_std_details();
echo $std_name."<br/>";
echo $std_id."<br/>";

?>

The output is :
Abhishek
01

Abhishek
01

where as the expected output is

Abhishek
01

Abhinay
00

The problem I guess is because the get_std_details function is returning an array.

I would like help from the community so that I can learn PHP better :D

Thanks in Advance
Abhishek Uppala

Re: Cloning an object when a function returns an array

Posted: Wed Nov 11, 2009 12:59 am
by josh
You commented out that line, which would be more apparent if you used

Code: Select all

tags and posted in the correct forum.