Php set resource type

PHP: settype() function

The settype() function is used to set the type of a variable.

Name Description Required /
Optional
Type
var_name The variable being converted. Required Mixed*
var_type Type of the variable. Possible values are : boolean, integer, float, string, array, object, null. Optional String

*Mixed: Mixed indicates that a parameter may accept multiple (but not necessarily all) types.

Return value:

TRUE on success or FALSE on failure.

Value Type: Boolean.

Practice here online :

Previous: serialize
Next: strval

Follow us on Facebook and Twitter for latest update.

PHP: Tips of the Day

PHP array delete by value (not key)

Using array_search() and unset, try the following:

if (($key = array_search($del_val, $messages)) !== false)

array_search() returns the key of the element it finds, which can be used to remove that element from the original array using unset(). It will return FALSE on failure, however it can return a false-y value on success (your key may be 0 for example), which is why the strict comparison !== operator is used.

The if() statement will check whether array_search() returned a value, and will only perform an action if it did.

  • Weekly Trends
  • Java Basic Programming Exercises
  • SQL Subqueries
  • Adventureworks Database Exercises
  • C# Sharp Basic Exercises
  • SQL COUNT() with distinct
  • JavaScript String Exercises
  • JavaScript HTML Form Validation
  • Java Collection Exercises
  • SQL COUNT() function
  • SQL Inner Join
  • JavaScript functions Exercises
  • Python Tutorial
  • Python Array Exercises
  • SQL Cross Join
  • C# Sharp Array Exercises

We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook

Источник

Php set resource type

While waiting for native support for typed arrays, here are a couple of alternative ways to ensure strong typing of arrays by abusing variadic functions. The performance of these methods is a mystery to the writer and so the responsibility of benchmarking them falls unto the reader.

PHP 5.6 added the splat operator (. ) which is used to unpack arrays to be used as function arguments. PHP 7.0 added scalar type hints. Latter versions of PHP have further improved the type system. With these additions and improvements, it is possible to have a decent support for typed arrays.

function typeArrayNullInt (? int . $arg ): void >

function doSomething (array $ints ): void (function (? int . $arg ) <>)(. $ints );
// Alternatively,
( fn (? int . $arg ) => $arg )(. $ints );
// Or to avoid cluttering memory with too many closures
typeArrayNullInt (. $ints );

function doSomethingElse (? int . $ints ): void /* . */
>

$ints = [ 1 , 2 , 3 , 4 , null ];
doSomething ( $ints );
doSomethingElse (. $ints );
?>

Both methods work with all type declarations. The key idea here is to have the functions throw a runtime error if they encounter a typing violation. The typing method used in doSomethingElse is cleaner of the two but it disallows having any other parameters after the variadic parameter. It also requires the call site to be aware of this typing implementation and unpack the array. The method used in doSomething is messier but it does not require the call site to be aware of the typing method as the unpacking is performed within the function. It is also less ambiguous as the doSomethingElse would also accept n individual parameters where as doSomething only accepts an array. doSomething’s method is also easier to strip away if native typed array support is ever added to PHP. Both of these methods only work for input parameters. An array return value type check would need to take place at the call site.

If strict_types is not enabled, it may be desirable to return the coerced scalar values from the type check function (e.g. floats and strings become integers) to ensure proper typing.

same data type and same value but first function declare as a argument type declaration and return int(7)
and second fucntion declare as a return type declaration but return int(8).

function argument_type_declaration(int $a, int $b) return $a+$b;
>

function return_type_declaration($a,$b) :int return $a+$b;
>

Источник

settype

Возвращает true в случае успешного выполнения или false в случае возникновения ошибки.

Примеры

Пример #1 Пример использования settype()

$foo = «5bar» ; // строка
$bar = true ; // булевое значение

settype ( $foo , «integer» ); // $foo теперь 5 (целое)
settype ( $bar , «string» ); // $bar теперь «1» (строка)
?>

Примечания

Замечание:

Максимальное значение для «int» равно PHP_INT_MAX .

Смотрите также

User Contributed Notes 17 notes

Note that you can’t use this to convert a string ‘true’ or ‘false’ to a boolean variable true or false as a string ‘false’ is a boolean true. The empty string would be false instead.

$var = «true» ;
settype ( $var , ‘bool’ );
var_dump ( $var ); // true

$var = «false» ;
settype ( $var , ‘bool’ );
var_dump ( $var ); // true as well!

$var = «» ;
settype ( $var , ‘bool’ );
var_dump ( $var ); // false
?>

Just a quick note, as this caught me out very briefly:

settype() returns bool, not the typecasted variable — so:

$blah = settype($blah, «int»); // is wrong, changes $blah to 0 or 1
settype($blah, «int»); // is correct

Hope this helps someone else who makes a mistake.. 😉

Using settype is not the best way to convert a string into an integer, since it will strip the string wherever the first non-numeric character begins. The function intval($string) does the same thing.

If you’re looking for a security check, or to strip non-numeric characters (such as cleaning up phone numbers or ZIP codes), try this instead:

you must note that this function will not set the type permanently! the next time you set the value of that variable php will change its type as well.

/*
This example works 4x faster than settype() function in PHP-CGI 5.4.13 and
8x faster in PHP-CGI 7.1.3(x64) for windows
*/

If you attempt to convert the special $this variable from an instance method (only in classes) :
* PHP will silently return TRUE and leave $this unchanged if the type was ‘bool’, ‘array’, ‘object’ or ‘NULL’
* PHP will generate an E_NOTICE if the type was ‘int’, ‘float’ or ‘double’, and $this will not be casted
* PHP will throw a catchable fatal error when the type is ‘string’ and the class does not define the __toString() method
Unless the new variable type passed as the second argument is invalid, settype() will return TRUE. In all cases the object will remain unchanged.
// This was tested with PHP 7.2
class Foo function test () printf ( «%-20s %-20s %s\n» , ‘Type’ , ‘Succeed?’ , ‘Converted’ );

// settype() should throw a fatal error, as $this cannot be re-assigned
printf ( «%-20s %-20s %s\n» , ‘bool’ , settype ( $this , ‘bool’ ), print_r ( $this , TRUE ));
printf ( «%-20s %-20s %s\n» , ‘int’ , settype ( $this , ‘int’ ), print_r ( $this , TRUE ));
printf ( «%-20s %-20s %s\n» , ‘float’ , settype ( $this , ‘float’ ), print_r ( $this ));
printf ( «%-20s %-20s %s\n» , ‘array’ , settype ( $this , ‘array’ ), print_r ( $this , TRUE ));
printf ( «%-20s %-20s %s\n» , ‘object’ , settype ( $this , ‘object’ ), print_r ( $this , TRUE ));
printf ( «%-20s %-20s %s\n» , ‘unknowntype’ , settype ( $this , ‘unknowntype’ ), print_r ( $this , TRUE ));
printf ( «%-20s %-20s %s\n» , ‘NULL’ , settype ( $this , ‘NULL’ ), print_r ( $this , TRUE ));
printf ( «%-20s %-20s %s\n» , ‘string’ , settype ( $this , ‘string’ ), print_r ( $this , TRUE ));
>
>
$a = new Foo ();
$a -> test ();
?>
Here is the result :
Type Succeed? Converted
bool 1 Foo Object
(
)

Notice: Object of class Foo could not be converted to int in C:\php\examples\oop-settype-this.php on line 9

Notice: Object of class Foo could not be converted to float in C:\php\examples\oop-settype-this.php on line 10

Warning: settype(): Invalid type in C:\php\examples\oop-settype-this.php on line 14

Catchable fatal error: Object of class Foo could not be converted to string in C:\php\examples\oop-settype-this.php on line 15

If the class Foo implements __toString() :
class Foo // .
function __toString () return ‘Foo object is awesome!’ ;
>
// .
>
?>
So the first code snippet will not generate an E_RECOVERABLE_ERROR, but instead print the same string as for the other types, and not look at the one returned by the __toString() method.

Источник

Php set resource type

Resource — это специальная переменная, содержащая ссылку на внешний ресурс. Ресурсы создаются и используются специальными функциями. Полный перечень этих функций и соответствующих типов ресурсов ( resource ) смотрите в приложении.

Смотрите также описание функции get_resource_type() .

Преобразование в ресурс

Поскольку тип resource содержит специальные указатели на открытые файлы, соединения с базой данных, области изображения и тому подобное, преобразование в этот тип не имеет смысла.

Освобождение ресурсов

Благодаря системе подсчёта ссылок, введённой в Zend Engine, определение отсутствия ссылок на ресурс происходит автоматически, после чего он освобождается сборщиком мусора. Поэтому очень редко требуется освобождать память вручную.

Замечание: Постоянные соединения с базами данных являются исключением из этого правила. Они не уничтожаются сборщиком мусора. Подробнее смотрите в разделе о постоянных соединениях.

User Contributed Notes 1 note

‘stream’ is a general resource type and can have specific subtypes (imap, pop, curl . ). Casting from ‘stream’ to them makes sense alright.

E.g. Making OAUTH2 work for imap, but still use the normal imap_ functions. Just open a ssl:// stream to the IMAP server with stream_socket_client(), send the «AUTHENTICATE XOAUTH2 . » authentication with valid token and then use the imap_ functions on the casted ‘stream’ to ‘imap’ resource.
Not being able to cast from ‘stream’ to ‘imap’ makes it necessary to use 3rd party solutions, like php-imap. Doesn’t have to be necessary, if the cast would be possible.

Источник

get_resource_type

If the given resource is a resource, this function will return a string representing its type. If the type is not identified by this function, the return value will be the string Unknown .

This function will return null and generate an error if resource is not a resource .

Examples

Example #1 get_resource_type() example

$fp = fopen ( «foo» , «w» );
echo get_resource_type ( $fp ) . «\n» ;

// As of PHP 8.0.0, the following does not work anymore. The curl_init function returns a CurlHandle object now.
$c = curl_init ();
echo get_resource_type ( $c ) . «\n» ;
?>

Output of the above example in PHP 7:

See Also

User Contributed Notes 1 note

Try this to know behavior:

function resource_test ( $resource , $name ) echo
‘[‘ . $name . ‘]’ ,
PHP_EOL ,
‘(bool)$resource => ‘ ,
$resource ? ‘TRUE’ : ‘FALSE’ ,
PHP_EOL ,
‘get_resource_type($resource) => ‘ ,
get_resource_type ( $resource ) ?: ‘FALSE’ ,
PHP_EOL ,
‘is_resoruce($resource) => ‘ ,
is_resource ( $resource ) ? ‘TRUE’ : ‘FALSE’ ,
PHP_EOL ,
PHP_EOL
;
>

$resource = tmpfile ();
resource_test ( $resource , ‘Check Valid Resource’ );

fclose ( $resource );
resource_test ( $resource , ‘Check Released Resource’ );

$resource = null ;
resource_test ( $resource , ‘Check NULL’ );
?>

It will be shown as.

[Check Valid Resource](bool)$resource => TRUE
get_resource_type($resource) => stream
is_resoruce($resource) => TRUE [Check Released Resource](bool)$resource => TRUE
get_resource_type($resource) => Unknown
is_resoruce($resource) => FALSE [Check NULL](bool)$resource => FALSE
get_resource_type($resource) => FALSE
Warning: get_resource_type() expects parameter 1 to be resource, null given in . on line 10
is_resoruce($resource) => FALSE

Источник

Читайте также:  Python трехместный условный оператор
Оцените статью