Home  >  Article  >  Backend Development  >  PHP data type conversion_PHP tutorial

PHP data type conversion_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 10:42:061158browse

PHP does not require (or support) explicit type definitions in variable definitions; the variable type is determined based on the context in which the variable is used. In other words, if a string value is assigned to the variable var, var becomes a string. If you assign an integer value to var, it becomes an integer.

An example of PHP's automatic type conversion is the plus sign "+". If any operand is a floating point number, all operands are treated as floating point numbers, and the result is also a floating point number. Otherwise the operands are interpreted as integers and the result is also an integer. Note that this does not change the types of the operands themselves; only how the operands are evaluated and the type of the expression itself is changed.

Type casting

The allowed casts are:

  • (int), (integer) - converted to integer
  • (bool), (boolean) - Convert to boolean
  • (float), (double), (real) - Convert to Float (float)
  • (string) - Convert to string (string)
  • (binary) - convert to binary string (string) (PHP 6)
  • (array) - Convert to array (array)
  • (object) - Convert to object (object)
  • (unset) - convert to NULL (PHP 5)

(binary) conversion will prefix the result with 'b', new in PHP 5.2.1.

Note that spaces and tabs are allowed within brackets

Convert string(string) literals and variables to binary string(string):

<?<span php
</span><span $binary</span> = (binary)<span $string</span><span ;
</span><span $binary</span> = b"binary string"<span ;
</span>?>

If you want to change the type of a variable, see settype();

settypeSet the type of variable

bool settype ( mixed $var , string $type )

Set the type of variable var to type.

Possible values ​​for

type are:

  • "boolean" (or "bool" since PHP 4.2.0)
  • "integer" (or "int" since PHP 4.2.0)
  • "float" (only available after PHP 4.2.0, "double" used in older versions is now deprecated)
  • "string"
  • “array”
  • "object"
  • "null" (since PHP 4.2.0)

Returns TRUE on success, or FALSE on failure.

intval(), floatval(), strval(), these three functions can also be converted

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/675205.htmlTechArticlePHP does not require (or does not support) explicit type definitions in variable definitions; the variable type is based on the use of the variable determined by the context. That is, if you assign a string value to...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn