Php set variable type

Php set variable type

Cast a string to binary using PHP < 5.2.1

I found it tricky to check if a posted value was an integer.

is_int ( $_POST [ ‘a’ ] ); //false
is_int ( intval ( «anything» ) ); //always true
?>

A method I use for checking if a string represents an integer value.

$foo [ ‘ten’ ] = 10 ; // $foo[‘ten’] is an array holding an integer at key «ten»
$str = » $foo [ ‘ten’]» ; // throws T_ENCAPSED_AND_WHITESPACE error
$str = » $foo [ ten ] » ; // works because constants are skipped in quotes
$fst = (string) $foo [ ‘ten’ ]; // works with clear intention
?>

It seems (unset) is pretty useless. But for people who like to make their code really compact (and probably unreadable). You can use it to use an variable and unset it on the same line:

$hello = ‘Hello world’ ;
print $hello ;
unset( $hello );

$hello = ‘Hello world’ ;
$hello = (unset) print $hello ;

?>

Hoorah, we lost another line!

It would be useful to know the precedence (for lack of a better word) for type juggling. This entry currently explains that «if either operand is a float, then both operands are evaluated as floats, and the result will be a float» but could (and I think should) provide a hierarchy that indicates, for instance, «between an int and a boolean, int wins; between a float and an int, float wins; between a string and a float, string wins» and so on (and don’t count on my example accurately capturing the true hierarchy, as I haven’t actually done the tests to figure it out). Thanks!

May be expected, but not stated ..
Casting to the existing (same) type has no effect.
$t = ‘abc’; // string ‘abc’
$u=(array) $t; // array 0 => string ‘abc’ $v=(array) $u; // array 0 => string ‘abc’

Correct me if I’m wrong, but that is not a cast, it might be useful sometimes, but the IDE will not reflect what’s really happening:

class MyObject /**
* @param MyObject $object
* @return MyObject
*/
static public function cast ( MyObject $object ) return $object ;
>
/** Does nothing */
function f () <>
>

class X extends MyObject /** Throws exception */
function f () < throw new exception (); >
>

$x = MyObject :: cast (new X );
$x -> f (); // Your IDE tells ‘f() Does nothing’
?>

However, when you run the script, you will get an exception.

In my much of my coding I have found it necessary to type-cast between objects of different class types.

More specifically, I often want to take information from a database, convert it into the class it was before it was inserted, then have the ability to call its class functions as well.

The following code is much shorter than some of the previous examples and seems to suit my purposes. It also makes use of some regular expression matching rather than string position, replacing, etc. It takes an object ($obj) of any type and casts it to an new type ($class_type). Note that the new class type must exist:

Читайте также:  border-bottom

Looks like type-casting user-defined objects is a real pain, and ya gotta be nuttin’ less than a brain jus ta cypher-it. But since PHP supports OOP, you can add the capabilities right now. Start with any simple class.
class Point protected $x , $y ;

public function __construct ( $xVal = 0 , $yVal = 0 ) $this -> x = $xVal ;
$this -> y = $yVal ;
>
public function getX () < return $this ->x ; >
public function getY () < return $this ->y ; >
>

$p = new Point ( 25 , 35 );
echo $p -> getX (); // 25
echo $p -> getY (); // 35
?>
Ok, now we need extra powers. PHP gives us several options:
A. We can tag on extra properties on-the-fly using everyday PHP syntax.
$p->z = 45; // here, $p is still an object of type [Point] but gains no capability, and it’s on a per-instance basis, blah.
B. We can try type-casting it to a different type to access more functions.
$p = (SuperDuperPoint) $p; // if this is even allowed, I doubt it. But even if PHP lets this slide, the small amount of data Point holds would probably not be enough for the extra functions to work anyway. And we still need the class def + all extra data. We should have just instantiated a [SuperDuperPoint] object to begin with. and just like above, this only works on a per-instance basis.
C. Do it the right way using OOP — and just extend the Point class already.
class Point3D extends Point protected $z ; // add extra properties.

public function __construct ( $xVal = 0 , $yVal = 0 , $zVal = 0 ) parent :: __construct ( $xVal , $yVal );
$this -> z = $zVal ;
>
public function getZ () < return $this ->z ; > // add extra functions.
>

$p3d = new Point3D ( 25 , 35 , 45 ); // more data, more functions, more everything.
echo $p3d -> getX (); // 25
echo $p3d -> getY (); // 35
echo $p3d -> getZ (); // 45
?>
Once the new class definition is written, you can make as many Point3D objects as you want. Each of them will have more data and functions already built-in. This is much better than trying to beef-up any «single lesser object» on-the-fly, and it’s way easier to do.

Re: the typecasting between classes post below. fantastic, but slightly flawed. Any class name longer than 9 characters becomes a problem. SO here’s a simple fix:

function typecast($old_object, $new_classname) if(class_exists($new_classname)) // Example serialized object segment
// O:5:»field»:9: $old_serialized_prefix = «O:».strlen(get_class($old_object));
$old_serialized_prefix .= «:\»».get_class($old_object).»\»:»;

$old_serialized_object = serialize($old_object);
$new_serialized_object = ‘O:’.strlen($new_classname).’:»‘.$new_classname . ‘»:’;
$new_serialized_object .= substr($old_serialized_object,strlen($old_serialized_prefix));
return unserialize($new_serialized_object);
>
else
return false;
>

Thanks for the previous code. Set me in the right direction to solving my typecasting problem. 😉

If you have a boolean, performing increments on it won’t do anything despite it being 1. This is a case where you have to use a cast.

I have 1 bar.
I now have 1 bar.
I finally have 2 bar.

Checking for strings to be integers?
How about if a string is a float?

Читайте также:  Возвращение нескольких значений функции php

/* checks if a string is an integer with possible whitespace before and/or after, and also isolates the integer */
$isInt = preg_match ( ‘/^\s*(9+)\s*$/’ , $myString , $myInt );

echo ‘Is Integer? ‘ , ( $isInt ) ? ‘Yes: ‘ . $myInt [ 1 ] : ‘No’ , «\n» ;

/* checks if a string is an integer with no whitespace before or after */
$isInt = preg_match ( ‘/^3+$/’ , $myString );

echo ‘Is Integer? ‘ , ( $isInt ) ? ‘Yes’ : ‘No’ , «\n» ;

/* When checking for floats, we assume the possibility of no decimals needed. If you MUST require decimals (forcing the user to type 7.0 for example) replace the sequence:
6+(\.1+)?
with
6+\.5+
*/

/* checks if a string is a float with possible whitespace before and/or after, and also isolates the number */
$isFloat = preg_match ( ‘/^\s*(1+(\.4+)?)\s*$/’ , $myString , $myNum );

echo ‘Is Number? ‘ , ( $isFloat ) ? ‘Yes: ‘ . $myNum [ 1 ] : ‘No’ , «\n» ;

/* checks if a string is a float with no whitespace before or after */
$isInt = preg_match ( ‘/^2+(\.1+)?$/’ , $myString );

echo ‘Is Number? ‘ , ( $isFloat ) ? ‘Yes’ : ‘No’ , «\n» ;

Источник

Php set variable type

Для получения типа переменной применяется функция gettype() , которая возвращает название типа переменной, например, integer (целое число), double (число с плавающей точкой), string (строка), boolean (логическое значение), null , array (массив), object (объект) или unknown type . Например:

Также есть ряд специальных функций, которые возвращают true или false в зависимости от того, представляет ли переменная определенный тип:

  • is_integer($a) : возвращает значение true , если переменная $a хранит целое число
  • is_string($a) : возвращает значение true , если переменная $a хранит строку
  • is_double($a) : возвращает значение true , если переменная $a хранит действительное число
  • is_numeric($a) : возвращает значение true , если переменная $a представляет целое или действительное число или является строковым представлением числа. Например:
$a = 10; $b = "10"; echo is_numeric($a); echo "
"; echo is_numeric($b);

Установка типа. Функция settype()

С помощью функции settype() можно установить для переменной определенный тип. Она принимает два параметра: settype(«Переменная», «Тип») . В качестве первого параметра используется переменная, тип которой надо установить, а в качестве второго — строковое описание типа, которое возвращается функцией gettype() .

Если удалось установить тип, то функция возвращает true , если нет — то значение false .

Например, установим для переменной целочисленный тип:

Поскольку переменная $a представляет действительное число 10.7, то его вполне можно преобразовать в целое число через отсечение дробной части. Поэтому в данном случае функция settype() возвратит true .

Преобразование типов

По умолчанию PHP при необходимости автоматически преобразует значение переменной из одного типа в другой. По этой причине явные преобразования в PHP не так часто требуются. Тем не менее мы можем их применять.

Для явного преобразования перед переменной в скобках указыется тип, в который надо выполнить преобразование:

$boolVar = false; $intVar = (int)$boolVar; // 0 echo "boolVar = $boolVar
intVar = $intVar";

В данном случае значение «false» пробразуется в значение типа int , которое будет храниться в переменной $intVar . А именно значение false преобразуется в число 0. После этого мы сможем использовать данное значение как число.

При использовании выражения echo для вывода на страницу передаваемые значения автоматически преобразуются в строку. И поскольку переменная boolVar равна false , ее значение будет преобазовано в пустую строку. Тогда как значение 0 преобразуется в строку «0».

В PHP могут применяться следующие преобразования:

  • (int), (integer) : преобразование в int (в целое число)
  • (bool), (boolean) : преобразование в bool
  • (float), (double), (real) : преобразование в float
  • (string) : преобразование в строку
  • (array) : преобразование в массив
  • (object) : преобразование в object

Источник

PHP: settype() function

The settype() function is used to set the type of a variable.

Name Description Required /
Optional
Type
var_name The variable being converted. Required Mixed*
var_type Type of the variable. Possible values are : boolean, integer, float, string, array, object, null. Optional String

*Mixed: Mixed indicates that a parameter may accept multiple (but not necessarily all) types.

Return value:

TRUE on success or FALSE on failure.

Value Type: Boolean.

Practice here online :

Previous: serialize
Next: strval

Follow us on Facebook and Twitter for latest update.

PHP: Tips of the Day

How to Sort Multi-dimensional Array by Value?

Try a usort, If you are still on PHP 5.2 or earlier, you’ll have to define a sorting function first:

function sortByOrder($a, $b) < return $a['order'] - $b['order']; >usort($myArray, 'sortByOrder');

Starting in PHP 5.3, you can use an anonymous function:

And finally with PHP 7 you can use the spaceship operator:

usort($myArray, function($a, $b) < return $a['order'] $b['order']; >);

To extend this to multi-dimensional sorting, reference the second/third sorting elements if the first is zero — best explained below. You can also use this for sorting on sub-elements.

usort($myArray, function($a, $b) < $retval = $a['order'] $b['order']; if ($retval == 0) < $retval = $a['suborder'] $b['suborder']; if ($retval == 0) < $retval = $a['details']['subsuborder'] $b['details']['subsuborder']; > > return $retval; >);

If you need to retain key associations, use uasort() — see comparison of array sorting functions in the manual

  • Weekly Trends
  • Java Basic Programming Exercises
  • SQL Subqueries
  • Adventureworks Database Exercises
  • C# Sharp Basic Exercises
  • SQL COUNT() with distinct
  • JavaScript String Exercises
  • JavaScript HTML Form Validation
  • Java Collection Exercises
  • SQL COUNT() function
  • SQL Inner Join
  • JavaScript functions Exercises
  • Python Tutorial
  • Python Array Exercises
  • SQL Cross Join
  • C# Sharp Array Exercises

We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook

Источник

PHP settype() Function

The settype() function converts a variable to a specific type.

Syntax

Parameter Values

Parameter Description
variable Required. Specifies the variable to convert
type Required. Specifies the type to convert variable to. The possible types are: boolean, bool, integer, int, float, double, string, array, object, null

Technical Details

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

Оцените статью