Перейти к содержанию

PHP Шпаргалки: различия между версиями

3289 байт добавлено ,  16:54, 12 ноября 2022
нет описания правки
Нет описания правки
 
(не показано 13 промежуточных версий этого же участника)
Строка 47: Строка 47:
!Описание
!Описание
!Примеры
!Примеры
!Приведение к
!Проверка на
|-
|-
|bool
|bool
Строка 52: Строка 54:
|булевый тип
|булевый тип
|true, false
|true, false
|(bool) $v
|is_bool($v)
|-
|-
|int
|int
Строка 57: Строка 61:
|целые числа
|целые числа
|15, 017, 0xf, 0b1111
|15, 017, 0xf, 0b1111
|(int) $v
|is_int($v)
|-
|-
|float
|float
Строка 62: Строка 68:
|числа с плав. точкой
|числа с плав. точкой
|0.01, 1e-2
|0.01, 1e-2
|(float) $v
|is_float($v)
|-
|-
|string
|string
Строка 67: Строка 75:
|строки
|строки
|'abc', "abc"
|'abc', "abc"
|(string) $v
|is_string($v)
|-
|-
|array
|array
Строка 73: Строка 83:
|[1,-0.1,'abc'],  
|[1,-0.1,'abc'],  
array('key' => 'value')
array('key' => 'value')
|(array) $v
|is_array($v)
|-
|-
|object
|object
Строка 79: Строка 91:
|new stdClass(),
|new stdClass(),
new class {}
new class {}
|(object) $v
|is_object($v)
|-
|-
|callable
|callable
Строка 85: Строка 99:
|function(){},
|function(){},
fn($x) => $x+1
fn($x) => $x+1
| -
|is_callable($v)
|-
|-
|iterable
|iterable
Строка 91: Строка 107:
|[1,2],
|[1,2],
(function() { yield 1; yield 2; })()
(function() { yield 1; yield 2; })()
| -
|is_iterable($v)
|-
|-
|resource
|resource
Строка 96: Строка 114:
|внешний ресурс
|внешний ресурс
|fopen('<nowiki>http://www.google.com'</nowiki>, 'r')
|fopen('<nowiki>http://www.google.com'</nowiki>, 'r')
| -
|is_resource($v)
|-
|-
|NULL
|NULL
Строка 101: Строка 121:
|нет значения
|нет значения
|null
|null
| -
|is_null($v)
|}
== Типы ошибок ==
{| class="wikitable"
|Значение
|Константа
|Выполнение
прерывается
|Описание
|-
|1
|'''<code>E_ERROR</code>'''
|style="background-color: #ff6666"|Да
|Фатальные неустранимые ошибки во время выполнения.
|-
|2
|'''<code>E_WARNING</code>'''
|style="background-color: #ffff66"|Нет
|Не фатальные предупреждения во время выполнения.
|-
|4
|'''<code>E_PARSE</code>'''
|style="background-color: #ff6666"|Да
|Ошибки на этапе компиляции. Невозможность обработать исходный код.
|-
|8
|'''<code>E_NOTICE</code>'''
|Нет
|Уведомление с указанием на возможную ошибку.
|-
|16
|'''<code>E_CORE_ERROR</code>'''
|style="background-color: #ff6666"|Да
|Фатальные ошибки ядра PHP.
|-
|32
|'''<code>E_CORE_WARNING</code>'''
|style="background-color: #ffff66"|Нет
|Предупреждения ядра PHP.
|-
|64
|'''<code>E_COMPILE_ERROR</code>'''
|style="background-color: #ff6666"|Да
|Фатальные ошибки на этапе компиляции от движка Zend.
|-
|128
|'''<code>E_COMPILE_WARNING</code>'''
|style="background-color: #ffff66"|Нет
|Предупреждения на этапе компиляции от движка Zend.
|-
|256
|'''<code>E_USER_ERROR</code>'''
|style="background-color: #ff6666"|Да
|Фатальные ошибки, вызванные пользователем через trigger_error().
|-
|512
|'''<code>E_USER_WARNING</code>'''
|style="background-color: #ffff66"|Нет
|Предупреждения, вызванные пользователем через trigger_error().
|-
|1024
|'''<code>E_USER_NOTICE</code>'''
|Нет
|Уведомления, вызванные пользователем через trigger_error().
|-
|2048
|'''<code>E_STRICT</code>'''
|Нет
|Предложения для лучшей совместимости с новыми версиями PHP
|-
|4096
|'''<code>E_RECOVERABLE_ERROR</code>'''
|style="background-color: #ff6666"|Да
|Фатальные ошибки с возможностью обработки с помощью set_error_handler().
|-
|8192
|'''<code>E_DEPRECATED</code>'''
|Нет
|Уведомления о коде, который не будет работать в следующих версиях PHP.
|-
|16384
|'''<code>E_USER_DEPRECATED</code>'''
|Нет
|Уведомления о устаревшем функционале, вызванные пользователем через trigger_error()
|-
|32767
|'''<code>E_ALL</code>'''
| -
|Все типы ошибок, предупреждений и уведомлений.
|}
|}
Полезный калькулятор ошибок https://maximivanov.github.io/php-error-reporting-calculator/


== Приведение типов ==
== Приведение типов ==
{| class="wikitable"
{| class="wikitable"
|+ Примеры приведения типов
|+ Примеры приведения типов в PHP 8+
! $v = ...
! $v = ...
!Тип
! gettype($v)
! gettype($v)
! (bool)$v
! (bool)$v
Строка 116: Строка 229:
|-
|-
! null
! null
| string(4) "NULL"
|NULL
| "NULL"


| bool(false)
| false


| int(0)
| int(0)
Строка 124: Строка 238:
| float(0)
| float(0)


| string(0) ""
| <code>""</code>


| []
| '''[ ]'''
| {}
| '''{ }**'''
|-
|-
! true
! true
| string(7) "boolean"
|bool
| '''"boolean"'''


| bool(true)
| true


| int(1)
| int(1)
Строка 138: Строка 253:
| float(1)
| float(1)


| string(1) "1"
| "1"


| [true]
| [0=>true]
| {"scalar":true}
| {"scalar":true}**
|-
|-
! false
! false
| string(7) "boolean"
|bool
| '''"boolean"'''


| bool(false)
| false


| int(0)
| int(0)
Строка 152: Строка 268:
| float(0)
| float(0)


| string(0) ""
| <code>""</code>


| [false]
| [0=>false]
| {"scalar":false}
| {"scalar":false}**
|-
|-
! 0
! 0
| string(7) "integer"
|int
| '''"integer"'''


| bool(false)
| false


| int(0)
| int(0)
Строка 166: Строка 283:
| float(0)
| float(0)


| string(1) "0"
| "0"


| [0]
| [0=>0]
| {"scalar":0}
| {"scalar":0}**
|-
|-
! 1
! 1
| string(7) "integer"
|int
| '''"integer"'''


| bool(true)
| true


| int(1)
| int(1)
Строка 180: Строка 298:
| float(1)
| float(1)


| string(1) "1"
| "1"


| [1]
| [0=>1]
| {"scalar":1}
| {"scalar":1}**
|-
|-
! 1.0
! 1.99
| string(6) "double"
|float
| '''"double"'''


| bool(true)
| true


| int(1)
| '''int(1)***'''


| float(1)
| float(1.99)


| string(1) "1"
| "1.99"


| [1]
| [0=>1.99]
| {"scalar":1}
| {"scalar":1.99}**
|-
|-
! M_PI
! M_PI
| string(6) "double"
|float
| '''"double"'''


| bool(true)
| true


| int(3)
| int(3)


| float(3.141592653589793)
| float(3.1...)


| string(15) "3.1415926535898"
| "3.14159..."


| [3.141592653589793]
| [0=>3.14159...]
| {"scalar":3.141592653589793}
| {"scalar":3.141...}**
|-
|-
! INF
! INF
| string(6) "double"
|float
| '''"double"'''


| bool(true)
| true


| int(0)
| '''int(0)'''


| float(INF)
| float(INF)


| string(3) "INF"
| '''"INF"'''


| array(1) {
| [0=>INF]
  [0]=>
  float(INF)
}


| object(stdClass)#5 (1) {
| {"scalar":INF}**
  ["scalar"]=>
  float(INF)
}


|-
|-
! NAN
! NAN
| string(6) "double"
|float
| '''"double"'''


| bool(true)
| '''true'''


| int(0)
| '''int(0)'''


| float(NAN)
| float(NAN)


| string(3) "NAN"
| '''"NAN"'''


| array(1) {
| [0=>NAN]
  [0]=>
  float(NAN)
}


| object(stdClass)#5 (1) {
| {"scalar":NAN}**
  ["scalar"]=>
  float(NAN)
}


|-
|-
! ""
! ""
| string(6) "string"
|string
| "string"


| bool(false)
| false


| int(0)
| int(0)
Строка 266: Строка 377:
| float(0)
| float(0)


| string(0) ""
| <code>""</code>


| [""]
| [0=><code>""</code>]
| {"scalar":""}
| {"scalar":<code>""</code>}**
|-
|-
! "0"
! "0"
| string(6) "string"
|string
| "string"


| bool(false)
| '''false'''


| int(0)
| int(0)
Строка 280: Строка 392:
| float(0)
| float(0)


| string(1) "0"
| "0"


| ["0"]
| [0=>"0"]
| {"scalar":"0"}
| {"scalar":"0"}**
|-
|-
! "1"
! "1"
| string(6) "string"
|string
| "string"


| bool(true)
| true


| int(1)
| int(1)
Строка 294: Строка 407:
| float(1)
| float(1)


| string(1) "1"
| "1"


| ["1"]
| [0=>"1"]
| {"scalar":"1"}
| {"scalar":"1"}**
|-
|-
! "true"
! "true"
| string(6) "string"
|string
| "string"


| bool(true)
| true


| int(0)
| '''int(0)'''


| float(0)
| float(0)


| string(4) "true"
| "true"


| ["true"]
| [0=>"true"]
| {"scalar":"true"}
| {"scalar":"true"}**
|-
|-
! "false"
! "false"
| string(6) "string"
|string
| "string"


| bool(true)
| '''true'''


| int(0)
| int(0)
Строка 322: Строка 437:
| float(0)
| float(0)


| string(5) "false"
| "false"


| ["false"]
| [0=>"false"]
| {"scalar":"false"}
| {"scalar":"false"}**
|-
|-
! "null"
! [ ]
| string(6) "string"
|array
| "array"


| bool(true)
| '''false'''


| int(0)
| '''int(0)'''


| float(0)
| float(0)


| string(4) "null"
| style="background-color: #ffff66" | '''"Array" *'''
 
| [ ]
| ["null"]
| { }**
| {"scalar":"null"}
|-
|-
! []
! [1,2]
| string(5) "array"
|array
 
| "array"
| bool(false)
 
| int(0)


| float(0)
| true
 
|
Warning: Array to string conversion in /home/user/scripts/code.php on line 125
string(5) "Array"
 
| []
| {}
|-
! [0]
| string(5) "array"
 
| bool(true)


| int(1)
| int(1)
Строка 366: Строка 466:
| float(1)
| float(1)


|  
| style="background-color: #ffff66" | '''"Array" *'''
Warning: Array to string conversion in /home/user/scripts/code.php on line 125
| [0=>1,1=>2]
string(5) "Array"
| {'''"0"''':1,'''"1"''':2}**
 
| [0]
| {"0":0}
|-
|-
! ["abc"]
! ["3"=>"a","B",4=>"c"]
| string(5) "array"
|array
| "array"


| bool(true)
| true


| int(1)
| int(1)
Строка 382: Строка 480:
| float(1)
| float(1)


|  
| style="background-color: #ffff66" | '''"Array" *'''
Warning: Array to string conversion in /home/user/scripts/code.php on line 125
| '''[3=>"a",4=>"c"]'''
string(5) "Array"
| {'''"3"''':"a",'''"4"''':"c"}**
 
| ["abc"]
| {"0":"abc"}
|-
|-
! ["a"=>"b"]
! ["a"=>"b","b"]
| string(5) "array"
|array
| "array"


| bool(true)
| true


| int(1)
| int(1)
Строка 398: Строка 494:
| float(1)
| float(1)


|  
| style="background-color: #ffff66" | '''"Array" *'''
Warning: Array to string conversion in /home/user/scripts/code.php on line 125
| ["a"=>"b",'''0=>'''"b"]
string(5) "Array"
| {"a":"b",'''"0"''':"b"}**
 
| {"a":"b"}
| {"a":"b"}
|-
|-
! [["a"=>"b"]]
! [["a"=>"b"]]
| string(5) "array"
|array
| "array"


| bool(true)
| true


| int(1)
| int(1)
Строка 414: Строка 508:
| float(1)
| float(1)


|  
| style="background-color: #ffff66" | '''"Array" *'''
Warning: Array to string conversion in /home/user/scripts/code.php on line 125
| [["a"=>"b]]
string(5) "Array"
| {"0":'''["a"=>"b"]'''}**
 
| [{"a":"b"}]
| {"0":{"a":"b"}}
|-
|-
! new stdClass()
! new stdClass()
| string(6) "object"
|object
| "object"


| bool(true)
| '''true'''


|  
| style="background-color: #ffff66" | '''int(1)*'''
Warning: Object of class stdClass could not be converted to int in /home/user/scripts/code.php on line 125
| style="background-color: #ffff66" | float(1)*
int(1)
| style="background-color: #ff6666" | '''Fatal error'''
 
| [ ]
|  
| { }**
Warning: Object of class stdClass could not be converted to float in /home/user/scripts/code.php on line 125
float(1)
 
| Object of class stdClass could not be converted to string
| []
| {}
|-
|-
! new class {function __toString(){ return "value"; }}
! <small>Object с методом __toString</small>
| string(6) "object"
|object
| "object"


| bool(true)
| true


|  
| style="background-color: #ffff66" | int(1)*
Warning: Object of class class@anonymous could not be converted to int in /home/user/scripts/code.php on line 125
int(1)


|  
| style="background-color: #ffff66" | float(1)*
Warning: Object of class class@anonymous could not be converted to float in /home/user/scripts/code.php on line 125
float(1)


| string(5) "value"
| "''<small>из __toString</small>''"


| []
| [<small>''поля из объекта''</small>]
| {}
| ''object(SomeClass)''
|-
|-
! (function() { yield 1; yield 2; })()
!fn($x) => $x+1
| string(6) "object"
|callable
 
|'''"object"'''
| bool(true)
|true
| style="background-color: #ffff66" | int(1)*
| style="background-color: #ffff66" | float(1)*
| style="background-color: #ff6666" | '''Fatal error'''
|[''<small>object(Closure)</small>'']
|''object(Closure)''
|-
! <small>(function() { yield ...; })()</small>
|iterable
| '''"object"'''


|  
| true
Warning: Object of class Generator could not be converted to int in /home/user/scripts/code.php on line 125
int(1)


|  
| style="background-color: #ffff66" | int(1)*
Warning: Object of class Generator could not be converted to float in /home/user/scripts/code.php on line 125
float(1)


| Object of class Generator could not be converted to string
| style="background-color: #ffff66" | float(1)*
| []
| style="background-color: #ff6666" | '''Fatal error'''
| {}
| [ ]
| ''object(Generator)''
|-
|-
! fopen('file', 'r')
! fopen('xxx', 'r')
| string(8) "resource"
|resource
| "resource"


| bool(true)
| true


| int(6)
| '''int(?)'''


| float(6)
| '''float(?)'''


| string(14) "Resource id #6"
| "<small>Resource id #?</small>"


| array(1) {
| [<small>''resource…''</small>]
  [0]=>
  resource(6) of type (stream)
}


| object(stdClass)#5 (1) {
| {"scalar":''<small>resource…</small>''}
  ["scalar"]=>
  resource(6) of type (stream)
}


|-
|-
|colspan="25"| * ремарка
! <sub>Примечания:</sub>
| colspan="2" | <sub>* E_WARNING</sub>
| colspan="3" | <sub>** { } - обозначение для object(stdClass)</sub>
| colspan="3" | <sub>*** округление в меньшую сторону</sub>
|-
|-
|}
|}
До версии PHP < 7.3 при приведении массива к объекту ключи оставались цифрами: {0:1} вместо {"0":1}. До версии 8.0 типы ошибок были менее строгие. В остальном в старых версиях приведение работает аналогично.


== Объявление типов для строгой типизации ==
== Объявление типов для строгой типизации ==
Строка 1372: Строка 1460:
|-
|-
|}
|}
[[Категория:Шпаргалки]]