Page 1 of 1

Problem Cloning an object when a function returns an array

Posted: Wed Nov 11, 2009 12:31 am
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: Problem Cloning an object when a function returns an array

Posted: Wed Nov 11, 2009 1:51 am
by requinix
...Oh, I know...

Code: Select all

//list($std_name,$std_id)=$std1->get_std_details();
print_r($std1->get_std_details());

Code: Select all

//list($std_name,$std_id)=$std2->get_std_details();
print_r($std2->get_std_details());
Then take a guess what happened.

Re: Problem Cloning an object when a function returns an array

Posted: Wed Nov 11, 2009 2:54 am
by abhiuppu
@tasairis: Can you help me in knowing what is the difference between both? extracting the array elements by list() was not functioning whereas the solution you suggested is working fine.

Thanks :)
Abhishek Uppala