Jump to content

php7 - Scalar type declarations


Andy_Kemp

Recommended Posts

<?php

declare(strict_types = 1);

function test(string $username, int $age, float $price) : array {
    return array('Username' => $username, 'Age' => $age, 'Price' => $price);
}

$_get = array(
    'username' => '',
    'age' => '',
    'price' => '',
);

$_get = array_merge($_get, $_GET); 

print_r(test($_get['username'], $_get['age'], $_get['price']));

I am new with php7

 

So when i looked those examples i see test('test_username', 20, 20.01) but int and float are absolutely useless with $_POST, $_GET, Its always error. WITH int - must be of the type integer, string given. WITH float - must be of the type float, string given

Link to comment
Share on other sites

And your question is what exactly?

 

It's obvious that you cannot pass raw request parameters to a function that expects numeric types. So? Why would you want that? There should be a component in your application which validates the raw input, converts it when necessary and then passes the converted data on to other methods and functions. You shouldn't have $_GET and $_POST all over the place, anyway.

Link to comment
Share on other sites

Yeah. 100% what @Jacques1 said.  You seem to be unaware that everything sent through HTTP Request Method is sent as a string.  So you have "20" not 20, "102.99" not 102.99 etc.  This isn't usually a problem - as long as you are aware of it so that you can handle the data type as and when you need to.  Search the php manual for "typecasting" and you should quickly be able to get some use out of your numbers.

Link to comment
Share on other sites

 

Looks like you example was not meant to be implemented, but only to educate yourself, true?

 

While print_r() is helpful to quickly view data, var_dump() gives you more information.  Try the following, you will will see what is going on

$_get = array_merge($_get, $_GET); 
var_dump($_get);

Yes thats true

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.