I have a reference to some string. I need to copy (clone) that string.
This is what I tried

$newString = $refToString; //this just copies the ref - no new memory allocated
$newString = clone $refToString; //this creates "__clone method called on non-object" error

If anyone knows how to do this, please help!
Thanks

I have a reference to some string. I need to copy (clone) that string.
This is what I tried

$newString = $refToString; //this just copies the ref - no new memory allocated
$newString = clone $refToString; //this creates "__clone method called on non-object" error

If anyone knows how to do this, please help!
Thanks

I believe strings are always copied/cloned on either assignment or modification.

Try:

$str = "joe";
$str2 = $str;  
$str2 .= " blo"; // you have cloned $str to $str2 by modifying $str2

echo $str; // would give you: joe

I'm sure this holds for all PHP versions to date since strings are "basic" types.

Objects are referenced however in PHP5 and above. PHP4 Objects are referenced on assignment. But cloned on modification.

Yes, it works like it should. I just left it for a while, and when I got back It just worked like it should. I'm also unable to reproduce the problem.
\Thanks for your reply anyway!

I think clone is only used to clone object references on PHP 5. For some reason $refToString contained a string or null value result, that's why PHP indicated that error.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.