Available PHP Functions

Php all functions name

A function may be defined using syntax such as the following:

Example #1 Pseudo code to demonstrate function uses

Any valid PHP code may appear inside a function, even other functions and class definitions.

Function names follow the same rules as other labels in PHP. A valid function name starts with a letter or underscore, followed by any number of letters, numbers, or underscores. As a regular expression, it would be expressed thus: ^[a-zA-Z_\x80-\xff][a-zA-Z0-9_\x80-\xff]*$ .

Functions need not be defined before they are referenced, except when a function is conditionally defined as shown in the two examples below.

When a function is defined in a conditional manner such as the two examples shown. Its definition must be processed prior to being called.

Example #2 Conditional functions

/* We can’t call foo() from here
since it doesn’t exist yet,
but we can call bar() */

if ( $makefoo ) function foo ()
echo «I don’t exist until program execution reaches me.\n» ;
>
>

/* Now we can safely call foo()
since $makefoo evaluated to true */

function bar ()
echo «I exist immediately upon program start.\n» ;
>

Example #3 Functions within functions

function foo ()
function bar ()
echo «I don’t exist until foo() is called.\n» ;
>
>

/* We can’t call bar() yet
since it doesn’t exist. */

/* Now we can call bar(),
foo()’s processing has
made it accessible. */

All functions and classes in PHP have the global scope — they can be called outside a function even if they were defined inside and vice versa.

PHP does not support function overloading, nor is it possible to undefine or redefine previously-declared functions.

Note: Function names are case-insensitive for the ASCII characters A to Z , though it is usually good form to call functions as they appear in their declaration.

Both variable number of arguments and default arguments are supported in functions. See also the function references for func_num_args() , func_get_arg() , and func_get_args() for more information.

It is possible to call recursive functions in PHP.

Example #4 Recursive functions

Note: Recursive function/method calls with over 100-200 recursion levels can smash the stack and cause a termination of the current script. Especially, infinite recursion is considered a programming error.

User Contributed Notes

Источник

get_defined_functions

Whether disabled functions should be excluded from the return value.

Return Values

Returns a multidimensional array containing a list of all defined functions, both built-in (internal) and user-defined. The internal functions will be accessible via $arr[«internal»] , and the user defined ones using $arr[«user»] (see example below).

Changelog

Version Description
8.0.0 The default value of the exclude_disabled parameter has been changed from false to true .
7.0.15, 7.1.1 The exclude_disabled parameter has been added.

Examples

Example #1 get_defined_functions() example

function myrow ( $id , $data )
return «

$id $data

\n» ;
>

The above example will output something similar to:

Array ( [internal] => Array ( [0] => zend_version [1] => func_num_args [2] => func_get_arg [3] => func_get_args [4] => strlen [5] => strcmp [6] => strncmp . [750] => bcscale [751] => bccomp ) [user] => Array ( [0] => myrow ) )

See Also

  • function_exists() — Return true if the given function has been defined
  • get_defined_vars() — Returns an array of all defined variables
  • get_defined_constants() — Returns an associative array with the names of all the constants and their values
  • get_declared_classes() — Returns an array with the name of the defined classes

User Contributed Notes 11 notes

You can list all arguments using ReflectionFunction class. It’s not necessary to parse selected files/files as suggested by Nguyet.Duc.

Example:
function foo (& $bar , $big , $small = 1 ) <>
function bar ( $foo ) <>
function noparams () <>
function byrefandopt (& $the = ‘one’ ) <>

$functions = get_defined_functions ();
$functions_list = array();
foreach ( $functions [ ‘user’ ] as $func ) $f = new ReflectionFunction ( $func );
$args = array();
foreach ( $f -> getParameters () as $param ) $tmparg = » ;
if ( $param -> isPassedByReference ()) $tmparg = ‘&’ ;
if ( $param -> isOptional ()) $tmparg = ‘[‘ . $tmparg . ‘$’ . $param -> getName () . ‘ = ‘ . $param -> getDefaultValue () . ‘]’ ;
> else $tmparg .= ‘&’ . $param -> getName ();
>
$args [] = $tmparg ;
unset ( $tmparg );
>
$functions_list [] = ‘function ‘ . $func . ‘ ( ‘ . implode ( ‘, ‘ , $args ) . ‘ )’ . PHP_EOL ;
>
print_r ( $functions_list );
?>

Output:
Array
(
[0] => function foo ( &&bar, &big, [$small = 1] )

[3] => function byrefandopt ( [&$the = one] )

At least with PHP 4.2.3 on a GNU/Linux/Apache platform, get_defined_functions() returns user-defined functions as all-lower case strings regardless of how the functions are capitalized when they are defined.

Here’s a useful trick with the get_defined_functions function — show all available functions with a link to the documentation (you can even change the mirror it goes to):

// the number of cols in our table
$num_cols = 3 ;

$ar = get_defined_functions ();
$int_funct = $ar [ internal ];
sort ( $int_funct );
$count = count ( $int_funct );
?>


functions
available on
print $_SERVER [ SERVER_NAME ];
?>
( »
target=»phpwin»>php
version
)

for( $i = 0 ; $i < $count ; $i ++) $doc = $php_host
. «manual/en/function.»
. strtr ( $int_funct [ $i ], «_» , «-» )
. «.php» ;
print »

\n» ;
if(( $i > 1 )
&& (( $i + $num_cols )% $num_cols ==( $num_cols — 1 )))
print «

\n

\n» ;
>
for( $i =( $num_cols -( $count % $num_cols )); $i > 0 ; $i —)
print »

\n» ;
?>

. «\» target=\»phpwin\»>»
. $int_funct [ $i ]
. «
 


Please note that functions created with create_function() are not returned.
(However that might change in a later version)

look at here, list all the defined function on your php-Version and give as well formatted output width links onto the php-manual:

To search for a function.


Search:

if (!empty( $_GET [ ‘search’ ])) echo ‘

‘ . ‘. $_GET [ ‘search’ ] . ‘»>’ .
‘Goto ‘ . $_GET [ ‘search’ ] . » .

‘ ;
>
?>

$country = ‘us’ ;
$functions = get_defined_functions ();
$functions = $functions [ ‘internal’ ];
$num = 0 ;
foreach( $functions as $function ) $num ++;
echo ‘

‘ ;
>
?>

‘ .
number_format ( $num ) . ‘
‘ . ‘. $function . ‘» href http://» rel=»nofollow» target=»_blank»>http://’ . $country . ‘.php.net/’ .
$function . ‘»>’ . $function . » . ‘


This is rather a simple non-confusing script to get the function names linked to its manual page on php.net. Hope it helps someone. Commented script is self explainatory

/*declare a variable to php manual of functions.
change the $lng to the region you want it for,
i-e en/es/de etc etc */
$lng = «es» ;
$url = «http://www.php.net/manual/» . $lng . «/function.» ;

// get defined functions in a variable (it will be a 2D array)
$functions = get_defined_functions ();

// Run nested foreach to get the function names
foreach( $functions as $function ) foreach ( $function as $functionName )

/* Since php manual is using hyphens instead of underscores
for functions, we will convert underscores to hyphen whereever
there is one. */
if( strpos ( $functionName , «_» ) !== false ) $functionForURL = str_replace ( «_» , «-» , $functionName );
> else $functionForURL = $functionName ;
>

Источник

Php all functions name

В самом PHP содержится достаточно большое количество встроенных функций и языковых конструкций. Также есть функции, которые требуют, чтобы PHP был собран с определёнными модулями, в противном случае будут генерироваться фатальные ошибки, вызванные использованием неизвестной функции. Например, для того чтобы использовать функции для работы с изображениями, например, imagecreatetruecolor() , необходимо собрать PHP с поддержкой GD . Или же для того, чтобы воспользоваться функцией mysqli_connect() , необходима поддержка модуля MySQLi. Тем не менее, есть много встроенных функций, которые доступны всегда: например, функции обработки строк и функции для работы с переменными. Вызвав phpinfo() или get_loaded_extensions() , можно узнать, поддержка каких модулей есть в используемом PHP. Также следует учесть, что поддержка некоторых дополнительных модулей включена по умолчанию, и что сама документация к PHP разбита по модулям. Ознакомьтесь с разделами Конфигурация, Установка, а также с документацией непосредственно к дополнительным модулям для получения более детальной информации о том, как настроить PHP.

Более подробную информацию о том, как следует читать и интерпретировать прототипы функций, вы можете найти в разделе Как читать определения функции. Очень важно понимать, что возвращает функция, или как именно она модифицирует передаваемые аргументы. Например, функция str_replace() возвращает модифицированную строку, в то время как функция usort() работает с фактически переданной переменной. Каждая страница документации также содержит информацию, которая специфична для данной функции, например, информацию о передаваемых параметрах, изменениях в поведении, возвращаемых значениях в случае как удачного, так и неудачного выполнения, доступности функции в различных версиях. Знание и применение этих (порой даже незаметных) нюансов очень важно для написания корректного PHP-кода.

Замечание: Если в функцию передаются не те аргументы, которые она ожидает, например, массив ( array ) вместо строки ( string ), возвращаемое значение функции не определено. Скорее всего в этом случае будет возвращён null , но это просто соглашение, на него нельзя полагаться. Начиная с PHP 8.0.0, в этом случае должно быть выброшено исключение TypeError .

Замечание:

Скалярные типы для встроенных функций по умолчанию являются допускающими значение null в принудительном режиме. Начиная с PHP 8.1.0, передача null в параметр встроенной функции, который не объявлен как допускающий значение null , не рекомендуется и в принудительном режиме выдаётся уведомление об устаревании, чтобы соответствовать поведению пользовательских функций, где скалярные типы должны быть явно помечены как допускающие значение null .

Например, функция strlen() ожидает, что параметр $string будет строкой ( string ), не допускающей значение null . По историческим причинам PHP позволяет передавать null для этого параметра в принудительном режиме и параметр неявно приводится к строке ( string ), в результате чего получается значение «» . В строгом режиме выбрасывается исключение TypeError .

var_dump ( strlen ( null ));
// «Deprecated: Passing null to parameter #1 ($string) of type string is deprecated» начиная с PHP 8.1.0
// int(0)

var_dump ( str_contains ( «foobar» , null ));
// «Deprecated: Passing null to parameter #2 ($needle) of type string is deprecated» начиная с PHP 8.1.0
// bool(true)
?>

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

Источник

Читайте также:  Php параметры в другой
Оцените статью