Monday 12 October 2009

Learning PHP - Examining Variable Types

Programming is all about data and most languages take some trouble over classifying what kind of data they are working with. PHP's classes of data type are:
  • Integer
  • Float
  • Boolean
  • Array
  • Object
  • Null
  • Variable
PHP is described as being weakly or dynamically typed. This simply means that it works out the data type by looking at it rather than by you assigning it. For example:
  • $IssueNumber="0"; assigns integer type
  • $formulationpercentage="0.00"; assigns float type
Variables can be quickly reassigned to a new type. For instance if you add the line $IssueNumber="hello" it would be reassigned to a string type. This ability to change file types on the fly can be extremely useful.

Type Casting
You can pretend that a variable or a value is of a different type by using a type cast. All you have to do is put the temporary type in brackets in front of the variable you are interested in.
  • $IssueNumber="0"; assigns integer type
  • $formulationpercentage=(float)$IssueNumber
The second line takes the value stored in IssueNumber , interprets it as a float and stores it in fomulationpercentage.

Variable Variables

PHP provides one other type of variable. Variable variables enable you to change the name of a variable dynamically.

No comments: