Php только целые числа
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
?>?php
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:
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?
/* checks if a string is an integer with possible whitespace before and/or after, and also isolates the integer */
$isInt = preg_match ( ‘/^\s*(3+)\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 ( ‘/^9+$/’ , $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:
5+(\.8+)?
with
5+\.9+
*/
/* checks if a string is a float with possible whitespace before and/or after, and also isolates the number */
$isFloat = preg_match ( ‘/^\s*(4+(\.1+)?)\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+(\.3+)?$/’ , $myString );
echo ‘Is Number? ‘ , ( $isFloat ) ? ‘Yes’ : ‘No’ , «\n» ;
Целые числа
Целые числа могут быть указаны в десятичной (основание 10), шестнадцатеричной (основание 16), восьмеричной (основание 8) или двоичной (основание 2) системе счисления, с необязательным предшествующим знаком (- или +).
Двоичная запись integer доступна начиная с PHP 5.4.0.
Для записи в восьмеричной системе счисления, необходимо поставить пред числом 0 (ноль). Для записи в шестнадцатеричной системе счисления, необходимо поставить перед числом 0x. Для записи в двоичной системе счисления, необходимо поставить перед числом 0b
Пример #1 Целые числа
$a = 1234 ; // десятичное число
$a = — 123 ; // отрицательное число
$a = 0123 ; // восьмеричное число (эквивалентно 83 в десятичной системе)
$a = 0x1A ; // шестнадцатеричное число (эквивалентно 26 в десятичной системе)
$a = 0b11111111 ; // двоичное число (эквивалентно 255 в десятичной системе)
?>?php
Формально, структуру целых чисел можно записать так:
десятичные : 91* | 0 шестнадцатеричные : 0[xX][0-9a-fA-F]+ восьмеричные : 03+ двоичные : 0b[01]+ целые : [+-]?десятичные | [+-]?шестнадцатеричные | [+-]?восьмеричные | [+-]?двоичные
Размер integer зависит от платформы, хотя, как правило, максимальное значение примерно равно 2 миллиардам (это 32-битное знаковое). 64-битные платформы обычно имеют максимальное значение около 9E18, кроме Windows, которая всегда 32-битная. PHP не поддерживает беззнаковые целые ( integer ). С версии PHP 4.4.0 и PHP 5.0.5 размер integer может быть определен с помощью константы PHP_INT_SIZE , а его максимальное значение — с помощью константы PHP_INT_MAX .
Если в восьмеричном integer будет обнаружена неверная цифра (например, 8 или 9), оставшаяся часть числа будет проигнорирована.
Пример #2 Странности с восьмеричными числами
Переполнение целых чисел
Если PHP обнаружил, что число превышает размер типа integer , он будет интерпретировать его в качестве float . Аналогично, если результат операции лежит за границами типа integer , он будет преобразован в float .
Пример #3 Переполнение целых на 32-битных системах
$large_number = 2147483647 ;
var_dump ( $large_number ); // int(2147483647)
?php
$large_number = 2147483648 ;
var_dump ( $large_number ); // float(2147483648)
$million = 1000000 ;
$large_number = 50000 * $million ;
var_dump ( $large_number ); // float(50000000000)
?>
Пример #4 Переполнение целых на 64-битных системах
$large_number = 9223372036854775807 ;
var_dump ( $large_number ); // int(9223372036854775807)
?php
$large_number = 9223372036854775808 ;
var_dump ( $large_number ); // float(9.2233720368548E+18)
$million = 1000000 ;
$large_number = 50000000000000 * $million ;
var_dump ( $large_number ); // float(5.0E+19)
?>
В PHP не существует оператора деления целых чисел. Результатом 1/2 будет float 0.5. Если привести значение к integer , оно будет округлено вниз. Для большего контроля над округлением используйте функцию round() .
var_dump ( 25 / 7 ); // float(3.5714285714286)
var_dump ((int) ( 25 / 7 )); // int(3)
var_dump ( round ( 25 / 7 )); // float(4)
?>?php
Преобразование в целое
Для явного преобразования в integer , используйте приведение (int) или (integer). Однако, в большинстве случаев, в приведении типа нет необходимости, так как значение будет автоматически преобразовано, если оператор, функция или управляющая структура требует аргумент типа integer . Значение также может быть преобразовано в integer с помощью функции intval() .
Если resource преобразуется в integer , то результатом будет уникальный номер ресурса, привязанный к resource во время исполнения PHP программы.
Из булевого типа
FALSE преобразуется в 0 (ноль), а TRUE — в 1 (единицу).
Из чисел с плавающей точкой
При преобразовании из float в integer , число будет округлено в сторону нуля.
Если число с плавающей точкой превышает размеры integer (обычно +/- 2.15e+9 = 2^31 на 32-битных системах и +/- 9.22e+18 = 2^63 на 64-битных системах, кроме Windows), результат будет неопределенным, так как float не имеет достаточной точности, чтобы вернуть верный результат. В этом случае не будет выведено ни предупреждения, ни даже замечания!
Никогда не приводите неизвестную дробь к integer , так как это иногда может дать неожиданные результаты.