PHP cast from string to int error - php

Hi when trying to cast from a string to int using int() I get the following error:
Call to undefined function int()
Why would this be?
intval() works just fine but I cannot use int() for some reason.

There is no int function; you must use proper typecasting syntax for this:
$b = (int) $a;
Or:
settype($a, 'int');

function int($string) {
return (int) $string;
}

Have you tried
$intVar = (int)$var;
If PHP is telling you that int() isn't a function, then it probably isn't.

Related

How to convert nullable variable to non nullable type?

I have function which will receive parameter ?string
public function func(?string $x): string
{
$x = trim(strtolower($x));
$x = preg_replace('/\s+/', ' ', $x);
$x = str_replace(' ', '-', $x);
return $x;
}
running ./vendor/bin/phpstan analyse give those errors:
Parameter #1 $str of function strtolower expects string, string|null given.
Parameter #3 $subject of function preg_replace expects array|string, string|null given.
Parameter #3 $subject of function str_replace expects array|string, string|null given.
strtolower needs string and preg_replace&str_replace need array|string what is the best way to solve this without changing param from ?string $x to string $x?
in otherwords how to change var type from string|null to string ?
While PHP can convert null to an empty string with casting, you really have to ask yourself why this function should even accept a null value in the first place.
If null means you have some default value for $x, then that seems perfectly logical, and you can use null coalescing to make $x the default string value if $x is null.
$x = $x ?? 'default';
However, the above could be more effectively resolved by defining 'default' in the signature:
function func(string $x = 'default')
But based on your code, there really isn't any reason for null to be passed to this function. In my opinion, that's a code smell and should not be allowed. This function only works with strings, so don't allow nulls to begin with. The null value should then be handled before it reaches this function, by the consumer.
I believe you may be able to typecast your value of $x,
example:
function foo(?string $x) : string {
$a = (string) $x;
return $a;
}
This should yield,
var_dump(foo("test"));
string(4) "test"
And,
var_dump(foo(null));
string(0) ""
Hope this is what you were looking for.

Magic function to cast object to integer in php 7

I like to program object oriented so I want to make my own IntegerObject class. But when I try to execute the following code:
$x = new IntegerObject(3)
echo $x / 3;
I get the error:
Object of class IntegerObject could not be converted to int
Is there a magic function like __toString() to cast an object to an integer?
Workaround
As PHP is dynamically type casting language you can magically cast to string and the PHP will cast it to integer:
$x = new IntegerObject(3);
echo "$x" / 3;
You can cast to an integer using the (int) operator:
$x = new IntegerObject(3);
var_dump((int) "$x" / 3);
That should show you that the result is an int.

PHP difference between int and integer

Is there any difference between int and integer in PHP?
Which is the newer or more recommended use?
$a = (int)"3 euros";
echo $a; // $a==3
$a = (integer)"3 euros";
echo $a; // $a==3
The difference arises when we use type hinting from php 7.0+
this is valid
function getId(): int
{
return $id;
}
this is not
function getId(): integer
{
return $id;
}
the second one will expect you to return an object of a 'class integer', which will cause a strange sentence:
Uncaught TypeError: Return value of getId() must be an instance of integer, integer returned in ...
No.
They are the same, they both cast the value to an integer, one is just terser by four characters.
Source.
Quoting the manual:
Converting to integer
To explicitly convert a value to integer, use either the (int) or
(integer) casts. ...
This is not quite true, there is actually a difference between int and integer.
Here a simple example:
//print_r('PHP version: '.phpversion().'<br />');
//PHP version: 5.5.23
$i = '1';
function testme(int $j){
print_r ($j);
}
testme(intval($i));
This little portion of code will print an "E_RECOVERABLE_ERROR"
since testme function is expecting 'int' and get 'integer' instead.

What does (int) $_GET['page'] mean in PHP?

I tried looking up (int) but could only find documentation for the function int() in the PHP manual.
Could someone explain to me what the above code does, and exactly how it works?
You can find it in the manual in the section type juggling: type casting. (int) casts a value to int and is a language construct, which is the reason that it looks "funny".
It convert (tries at least) whatever the value of the variable is to a integer. If there are any letter etc, in front it will convert to a 0.
<?php
$var = '1a';
echo $var; // 1a
echo (int) $var; //1
$var2 = 'a2';
echo $var2; //a2
echo (int) $var2; // 0
?>
(int) converts a value to an integer.
<?php
$test = "1";
echo gettype((int)$test);
?>
$ php test.php
integer
Simple example will make you understand:
var_dump((int)8);
var_dump((int)"8");
var_dump((int)"6a6");
var_dump((int)"a6");
var_dump((int)8.9);
var_dump((int)"8.9");
var_dump((int)"6.4a6");
Result:
int(8)
int(8)
int(6)
int(0)
int(8)
int(8)
int(6)
In PHP, (int) will cast the value following it to an int.
Example:
php > var_dump((int) "5");
int(5)
I believe the syntax was borrowed from C.
What you are looking at there is known as type casting - for more information, see the manual page on type juggling.
The above piece of code casts (or converts) $_GET['page'] to an integer.
this kind of syntax (int) is called type casting. Basically it takes the variable following it and tries to force it into being an int
(int) is same as int()
see
http://php.net/manual/en/language.types.integer.php
it casts the variable following it to integer. more info from documentation:
http://php.net/manual/en/language.types.type-juggling.php
Type casting in PHP works much as it does in C: the name of the
desired type is written in parentheses before the variable which is to
be cast.
The casts allowed are:
(int), (integer) - cast to integer
(bool), (boolean) - cast to boolean
(float), (double), (real) - cast to float
(string) - cast to string
(array) - cast to array (object) - cast to object
(unset) - cast to NULL

Convert object to integer in PHP

The value of $total_results = 10
$total_results in an object, according to gettype()
I cannot use mathematical operators on $total_results because it's not numeric
Tried $total_results = intval($total_results) to convert to an integer, but no luck
The notice I get is: Object of class Zend_Gdata_Extension_OpenSearchTotalResults could not be converted to int
How can I convert to an integer?
Does this work?
$val = intval($total_results->getText());
$results_numeric = (int) $total_results;
or maybe this:
$results_numeric = $total_results->count();
perhaps the object has a build in method to get it as an integer?
Otherwise try this very hacky approach (relys on __toString() returning that 10)
$total_results = $total_results->__toString();
$total_results = intval($total_results);
However if the object has a build in non-magic method, you should use that!
You can see the methods of the class here. Then you can try out the different methods yourself. There is a getText() method for example.
try
class toValue {
function __toString()
{
return '3'; // you must return a string
}
}
$a = new toValue;
var_dump("$a" + 2);
result:
int(5)

Categories