Are Type-Casting and SetType similar?

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
Goldeneye
Forum Newbie
Posts: 7
Joined: Wed Dec 24, 2008 10:32 pm

Are Type-Casting and SetType similar?

Post by Goldeneye »

I was just looking through the PHP Manual for ways to verify that my variables are strings, numbers, integers, etc. And came across Type-Casting. Then I came across the settype() function, and now I'm just curious, they do (essentially) the same thing, correct?
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Re: Are Type-Casting and SetType similar?

Post by Chris Corbyn »

I'd never seen the settype() function, but it sounds like they do the same thing yes ;)
Goldeneye
Forum Newbie
Posts: 7
Joined: Wed Dec 24, 2008 10:32 pm

Re: Are Type-Casting and SetType similar?

Post by Goldeneye »

http://ca3.php.net/manual/en/function.settype.php

Alright, that's what I thought too. It's just a redundancy. Thanks :)

Oh one more question (this is a bit of tangent):
Say you have a session variable named 'key' ($_SESSION['key']) (which is to used SQL queries) and you assign it upon a one-time script execution (such as logging-in) as $_SESSION['key'] = (string)$database['key'];

Would it better to assign a type-cast upon initialization, or type-cast it solely when using it in queries?
josh
DevNet Master
Posts: 4872
Joined: Wed Feb 11, 2004 3:23 pm
Location: Palm beach, Florida

Re: Are Type-Casting and SetType similar?

Post by josh »

Goldeneye wrote: It's just a redundancy.
Nope.

Code: Select all

 
$type = 'int';
// invalid: $a = ( $type )'5a';
settype( $a, $type ); //valid
Goldeneye
Forum Newbie
Posts: 7
Joined: Wed Dec 24, 2008 10:32 pm

Re: Are Type-Casting and SetType similar?

Post by Goldeneye »

jshpro2 wrote:
Goldeneye wrote: It's just a redundancy.
Nope.

Code: Select all

 
$type = 'int';
// invalid: $a = ( $type )'5a';
settype( $a, $type ); //valid
Thanks for the clarification. That makes sense seeing as the first (invalid) method requires a constant not a string (as $type would considered to be).
User avatar
Ambush Commander
DevNet Master
Posts: 3698
Joined: Mon Oct 25, 2004 9:29 pm
Location: New Jersey, US

Re: Are Type-Casting and SetType similar?

Post by Ambush Commander »

Of course, you could always do it with eval. :twisted:
Post Reply