Convert object to integer in PHP - 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)

Related

Does PHP declares variables passed to functions args by reference? [duplicate]

This question already has answers here:
Reference Guide: What does this symbol mean in PHP? (PHP Syntax)
(24 answers)
Closed 10 years ago.
I was trying to find this answer on Google, but I guess the symbol & works as some operator, or is just not generally a searchable term for any reason.. anyhow. I saw this code snippet while learning how to create WordPress plugins, so I just need to know what the & means when it precedes a variable that holds a class object.
//Actions and Filters
if (isset($dl_pluginSeries)) {
//Actions
add_action('wp_head', array(&$dl_pluginSeries, 'addHeaderCode'), 1);
//Filters
add_filter('the_content', array(&$dl_pluginSeries, 'addContent'));
}
This will force the variable to be passed by reference. Normally, a hard copy would be created for simple types. This can come handy for large strings (performance gain) or if you want to manipulate the variable without using the return statement, eg:
$a = 1;
function inc(&$input)
{
$input++;
}
inc($a);
echo $a; // 2
Objects will be passed by reference automatically.
If you like to handle a copy over to a function, use
clone $object;
Then, the original object is not altered, eg:
$a = new Obj;
$a->prop = 1;
$b = clone $a;
$b->prop = 2; // $a->prop remains at 1
The ampersand preceding a variable represents a reference to the original, instead of a copy or just the value.
See here: http://www.phpreferencebook.com/samples/php-pass-by-reference/
This passes something by reference instead of value.
See:
http://php.net/manual/en/language.references.php
http://php.net/manual/en/language.references.pass.php
I used it for sending a variable to a function, and have the function change the variable around. After the function is done, I don't need to return the function to the return value and set the new value to my variable.
Example
function fixString(&$str) {
$str = "World";
}
$str = "Hello";
fixString($str);
echo $str; //Outputs World;
Code without the &
function fixString($str) {
$str = "World";
return $str;
}
$str = "Hello";
$str = fixString($str);
echo $str; //Outputs World;

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.

How to treat string as a string and not as an int in PHP

I was reading PHP manual and I came across type juggling
I was confused, because I've never came across such thing.
$foo = 5 + "10 Little Piggies"; // $foo is integer (15)
When I used this code it returns me 15, it adds up 10 + 5 and when I use is_int() it returns me true ie. 1 where I was expecting an error, it later referenced me to String conversion to numbers where I read If the string starts with valid numeric data, this will be the value used. Otherwise, the value will be 0 (zero)
$foo = 1 + "bob3"; /* $foo is int though this doesn't add up 3+1
but as stated this adds 1+0 */
now what should I do if I want to treat 10 Little Piggies OR bob3 as a string and not as an int. Using settype() doesn't work either. I want an error that I cannot add 5 to a string.
If you want an error, you need to trigger an error:
$string = "bob3";
if (is_string($string))
{
trigger_error('Does not work on a string.');
}
$foo = 1 + $string;
Or if you like to have some interface:
class IntegerAddition
{
private $a, $b;
public function __construct($a, $b) {
if (!is_int($a)) throw new InvalidArgumentException('$a needs to be integer');
if (!is_int($b)) throw new InvalidArgumentException('$b needs to be integer');
$this->a = $a; $this->b = $b;
}
public function calculate() {
return $this->a + $this->b;
}
}
$add = new IntegerAddition(1, 'bob3');
echo $add->calculate();
This is by design as a result of PHP's dynamically typed nature and of course lack of an explicit type declaration requirement. Variable types are determined based on context.
Based on your example, when you do:
$a = 10;
$b = "10 Pigs";
$c = $a + $b // $c == (int) 20;
Calling is_int($c) will of course always evaluate to a boolean true because PHP has decided to convert the result of the statement to an integer.
If you're looking for an error by the interpreter, you won't get it since this is, like I mentioned, something built into the language. You might have to write a lot of ugly conditional code to test your data types.
Or, if you want to do that for testing arguments passed to your functions - that's the only scenario which I can think of where you might want to do this - you can trust the client invoking your function to know what they are doing. Otherwise, the return value can simply be documented to be undefined.
I know coming from other platforms and languages, that might be hard to accept, but believe it or not a lot of great libraries written in PHP follow that same approach.

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.

PHP cast from string to int error

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.

Categories