p2p.wrox.com Forums

Need to download code?

View our list of code downloads.


  Return to Index  

beginning_php thread: casting vs settype


Message #1 by "Steven Ambrose" <sambrose@a...> on Tue, 11 Feb 2003 07:48:05 -0600
Excuse my ignorance as I am new to programming (except for html) and want a full understanding of what I
am reading and learning.

My question is in ref to chapter 2 and the section on casting and settype.  I am trying to understand the difference between casting
and settype.  Am I understanding that they both accomplish the same task?  IF they are accomplishing 2 totaly different tasks, could
someone please explain for a totaly newbie in the world of programming.  Thank you in advance.

Steve
Message #2 by "Nikolai Devereaux" <yomama@u...> on Tue, 11 Feb 2003 13:15:41 -0800
> Excuse my ignorance as I am new to programming (except for html)
> and want a full understanding of what I am reading and learning.
>
> My question is in ref to chapter 2 and the section on casting and
> settype.  I am trying to understand the difference between casting
> and settype.  Am I understanding that they both accomplish the same
> task?  IF they are accomplishing 2 totaly different tasks, could
> someone please explain for a totaly newbie in the world of
> programming.  Thank you in advance.


Well, settype() can be (more or less) rewritten in PHP as:

function settype(& $var, $type)
{
   eval("\$var = ($type)\$var;");
}

(Notice that $var is accepted by reference; changes to $var within the
function will modify the original variable passed in.)


The main difference between casting and settype() is that casting doesn't
affect the original value of the variable.


$myvar   = "52";        // $myvar is a string.
$yourvar = (int)$myvar; // $myvar is still a string.
settype($myvar, "int"); // $myvar is now an int.

Similarly:

$myvar = "52";          // A string;
$myvar = (int)$myvar;   //  now it's an int.



Hope this helps,

Nik


  Return to Index