Problem Cloning an object when a function returns an array

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
abhiuppu
Forum Newbie
Posts: 3
Joined: Tue Nov 10, 2009 12:11 pm

Problem Cloning an object when a function returns an array

Post 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
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

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

Post 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.
abhiuppu
Forum Newbie
Posts: 3
Joined: Tue Nov 10, 2009 12:11 pm

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

Post 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
Post Reply