Automatic conversion from int to string in PHP - php

In PHP, I have a variable of the type Integer.
When I pass it to a function, it's converted to a string.
I tested it with var_dump. It's an integer when I call the function.
Directly after the function call, it's a string.
Code:
public function setId($id)
{
var_dump($id);
// call of method "checkIfInteger" --> is_int($arg)
}
EDIT: Ok guys, I got it. In my setId method, I had another check method that trimmed the parameter (&$id) - when I enter ' 10 ' for example, I worked with a (trimmed) string afterwards.
Another question:
I use intval, but intval('OK') returns an integer.
'25' should return true, 25 too, 2.5 should return false, and 'ok' too.
Is there a function available?

A variable is not converted to a string. Quick check:
<?php
function setId($id)
{
var_dump($id);
// call of method "checkIfInteger" --> is_int($arg)
}
$a = 1;
setId($a);
Result is: int(1)
Where is your $id comming from? How do you know that it's an int before the method call?

//Where ever you wanted an integer, why not try this.?
int $id = intval($id, 0);
Hope that helps

That depends on how you send the parameter to your function...
Seems like you sent the param like this...
setId("1");// which will be a string ofcourse...
Try sending as setId(1); you will get integer in your var_dump output.
EDIT :
<?php
$id=1;
if(gettype($id)=="integer")
{
setId($id);
}
else
{
echo "Function will not be called because ID is not an integer!";
}
function setId($id)
{
var_dump($id);
}

Related

How to get the string name of the argument's type hint?

Let us say we have this function:
function greetMe (string $name) {
echo '<br/>'.$name;
echo '<br/>'.gettype($name);
}
As you can see, we can get the type of the parameter $name.
Now I am interested to know if there is a possibility, within the body of this function, to know that I declared the type string and not some other type. Any hints?
In PHP 7 and later, you can use ReflectionParameter.getType.
Example #1 ReflectionParameter::getType() example
<?php
function someFunction(int $param, $param2) {}
$reflectionFunc = new ReflectionFunction('someFunction');
$reflectionParams = $reflectionFunc->getParameters();
$reflectionType1 = $reflectionParams[0]->getType();
$reflectionType2 = $reflectionParams[1]->getType();
echo $reflectionType1;
var_dump($reflectionType2);
The above example will output something similar to:
int
null

PHP store function in array

i want to store function in array
send the array to another page
then execute it
i already read Can you store a function in a PHP array but still don't know what to do
here's what i try
control.php (it start here)
<?php
function getFirstFunction(){ echo "first function executed"; }
$data = array();
$data[0] = getFirstFunction();
$data[1] = function(){ echo "second function executed"; };
$data[2] = function(){ require_once "additional.php"; };
$data[3] = "my string";
header('Location: view.php?data='.$data);
?>
additional.php
<?php echo "additional included" ?>
view.php
<?php
if( isset($_GET['data']) ){
foreach( $_GET['data'] as $temp ){
if( is_callable($temp) ){
$temp;
}else{
"its not a function";
}
}
}
?>
my error =
Warning: Invalid argument supplied for foreach() in D:\Workspace\Web\latihanns\php\get\view.php on line 4
EDIT
thanks for notify that this code its dangerous.i'm not use this code in real live. i just try to learn store function in array then call it. then i just curious how if i call it on another page. i just simply curious... i make my code look clear and simple here because i afraid if i wrote complicated code, no one will be here or my post will closed as too localized...
If you want to pass anything than string into URL, only option is convert it to string form which is reversible to original types. PHP offers function called serialize() which converts anything to string. After that, you can call unserialize() to convert string back to original data. So you have to change one line in control.php to this:
header('Location: view.php?data='.serialize($data));
In file view.php you have to change one line to this:
foreach( unserialize($_GET['data']) as $temp ){
But you have to fix more things than this. If you have callable variable, you can't invoke function with $variable, but with $variable(). It is good to mention, that in PHP does not matter if you have real function (anonymous function, Closure etc.) in variable, or if variable is simple string with name of exists function.
However you have even another bug in control.php. Code $data[0] = getFirstFunction(); will not pass function getFirstFunction an make it callable, it just calls the function and put its return value to variable. You can define getFirstFunction as anonymouse function like function in $data[1] or just pass it as string like $data[0] = 'getFirstFunction' which will work.
At the end - as anyone mentioned here - IT IS VERY DANGEROUS ans you shouldn't use this on public server.

Returning function result into array

I am passing an array to a function and expecting the function to store values in it. Here's my code
The Function -
function GetDetailsById ($iStudentId, $aDetailsId)
{
/* SQL */
while ($row = mysql_fetch_array($result))
{
array_push($aDetailsId, $row[0]);
}
}
Usage -
$aDetailsId = array();
$oDetailsTable->GetDetailsById("1", $aDetailsId)
When I try to do
print_r($aDetailsId)
the array shows nothing. Am I doing it the right way?
Your array needs to be passed by reference to the function ; which means the function should be defined this way :
function GetDetailsById ($iStudentId, & $aDetailsId)
{
// ...
}
For more informations, see Making arguments be passed by reference
Or you could have your function return its result -- which might be better idea (looking at the code that calls the function, you immediately know what it does) :
function GetDetailsById ($iStudentId)
{
$result = array();
// TODO here, fill $result with your data
return $result;
}
And call the function :
$aDetailsId = $oDetailsTable->GetDetailsById("1");
That's because parameters are passed by value by default, meaning only the value of the variable is passed into the function, not the variable itself. Whatever you do to the value inside the function does not affect the original outside the function.
Two options:
return the modified value from the function.
Pass the parameter by reference:
function GetDetailsById ($iStudentId, &$aDetailsId) ...
first count/check your resutl is contain any resultset. and try using '&' in parameter of array
function GetDetailsById ($iStudentId, &$aDetailsId)
Please change function declaration to,
function GetDetailsById ($iStudentId, &$aDetailsId)
There is one more mistake in array_push call. Change it to,
array_push($aDetailsId, $row[0]);

PHP function with variable as default value for a parameter

By default a PHP function uses $_GET variables. Sometimes this function should be called in an situation where $_GET is not set. In this case I will define the needed variables as parameter like: actionOne(234)
To get an abstract code I tried something like this:
function actionOne($id=$_GET["ID"])
which results in an error:
Parse error: syntax error, unexpected T_VARIABLE
Is it impossible to define an default parameter by using an variable?
Edit
The actionOne is called "directly" from an URL using the framework Yii. By handling the $_GET variables outside this function, I had to do this on an central component (even it is a simple, insignificant function) or I have to change the framework, what I don't like to do.
An other way to do this could be an dummy function (something like an pre-function), which is called by the URL. This "dummy" function handles the variable-issue and calls the actionOne($id).
No, this isn't possible, as stated on the Function arguments manual page:
The default value must be a constant
expression, not (for example) a
variable, a class member or a function
call.
Instead you could either simply pass in null as the default and update this within your function...
function actionOne($id=null) {
$id = isset($id) ? $id : $_GET['ID'];
....
}
...or (better still), simply provide $_GET['ID'] as the argument value when you don't have a specific ID to pass in. (i.e.: Handle this outside the function.)
function actionOne( $id=null ) {
if ($id === null) $id = $_GET['ID'];
}
But, i would probably do this outside of the function:
// This line would change, its just a for instance
$id = $id ? $id : $_GET['id'];
actionOne( $id );
You should get that id before you call the function. Checking for the existence of the parameter breaks encapsulation. You should do something like that:
if (isset($_GET["ID"])
{
$id = $_GET["ID"];
}
else
{
//$id = something else
}
function doSomethingWithID($id)
{
//do something
}
You could use constant variable
define('ID',$_GET["ID"]);
function($id = _ID_){
//code
}
Yes it is impossible.
The default has to be a static variable:
function actionOne( $id='something') {
//code
}
Easy peanuts! (Might contain minor mistakes, errors or typos!)
You need a helper function, which will call you main function recursively, but having NULL as default:
Wrong: function actionOne($id=$_GET["ID"])
Right:
function actionOne($id) {...}
function actionOnewithID($id=NULL) {
if (NULL==$id){actionOne($_GET["ID"]);}
else {actionOne($id);
}
And if you need to return a value:
function actionOne($id) {...}
function actionOnewithID($id=NULL) {
if (NULL==$id){return(actionOne($_GET["ID"]));}
else {return(actionOne($id));
}
I hope this helps!
shortest way is:
function actionOne($id = null)
{
$id = $id ?? $_GET["ID"];
...
}

PHP Convert String to an array or object if it represents one

I have a function that prints information to the page, it does this because it checks if that value exists every time and outputs an error if it doesn't. Due to the unknown nature of what is being sent to this function it always arrives as a string, I can't change this.
Is it possible for this function to interpret strings such as "array[0]" and "object.something" and return that value instead of looking for the value as an index in $this
E.g.
private array = array("stuff");
$this->printValue("string");
$this->printValue("array[0]");
$this->printValue("object.name"); //Some specified object
public function printValue($key) {
if(isset($this->$key)) {
echo $this->$key;
} else {
die($key.' doesn\'t exist');
}
}
Would echo:
string
stuff
thename
Maybe this example helps:
class Example {
public function __construct() {
$this->foo = array(9, 8, 7);
$this->bar = (object) array('attr1' => 'val1', 'attr2' => 'val2');
$this->baz = 'abcde';
}
public function printValue($key) {
echo eval('return $this->' . $key . ';') . "\n";
}
}
$example = new Example();
$example->printValue('foo[0]'); # prints 9
$example->printValue('bar->attr1'); # prints val1
$example->printValue('baz'); # prints abcde
However, take into account that eval poses security risks because it can execute any PHP code and it may cause fatal errors. Using variable variables is safer, though not as general. Anyway, the input of these risky functions must be always validated.
I think the bigger question is, are you trying to use array[0] as an index for something you're trying to reference? I'm assuming so, otherwise you could access the data from those items listed. So, if you ARE wanting to use the array[0] as an index-identifier, then you could do something like:
private data_array['array[0]'] = "stuff";
$this->printValue(data_array['array[0]']);
im not sure but i think you want $pie = print_r($var,true) it sends the string as a return value not printing out

Categories