Php load zend extension

Php load zend extension

The list of command line options provided by the PHP binary can be queried at any time by running PHP with the -h switch:

Usage: php [options] [-f] [--] [args. ] php [options] -r [--] [args. ] php [options] [-B ] -R [-E ] [--] [args. ] php [options] [-B ] -F [-E ] [--] [args. ] php [options] -- [args. ] php [options] -a -a Run interactively -c | Look for php.ini file in this directory -n No php.ini file will be used -d foo[=bar] Define INI entry foo with value 'bar' -e Generate extended information for debugger/profiler -f Parse and execute . -h This help -i PHP information -l Syntax check only (lint) -m Show compiled in modules -r Run PHP without using script tags -B Run PHP before processing input lines -R Run PHP for every input line -F Parse and execute for every input line -E Run PHP after processing all input lines -H Hide any passed arguments from external tools. -S : Run with built-in web server. -t Specify document root for built-in web server. -s Output HTML syntax highlighted source. -v Version number -w Output source with stripped comments and whitespace. -z Load Zend extension . args. Arguments passed to script. Use -- args when first argument starts with - or script is read from stdin --ini Show configuration file names --rf Show information about function . --rc Show information about class . --re Show information about extension . --rz Show information about Zend extension . --ri Show configuration for extension .

Run PHP interactively. For more information, see the Interactive shell section.

Читайте также:  Onclick button in javascript examples

Bind Path for external FASTCGI Server mode ( CGI only).

Do not chdir to the script’s directory ( CGI only).

Quiet-mode. Suppress HTTP header output ( CGI only).

Measure execution time of script repeated count times ( CGI only).

Specifies either a directory in which to look for php.ini , or a custom INI file (which does not need to be named php.ini ), e.g.:

$ php -c /custom/directory/ my_script.php $ php -c /custom/directory/custom-file.ini my_script.php

If this option is not specified, php.ini is searched for in the default locations.

Set a custom value for any of the configuration directives allowed in php.ini . The syntax is:

-d configuration_directive[=value]
# Omitting the value part will set the given configuration directive to "1" $ php -d max_execution_time -r '$foo = ini_get("max_execution_time"); var_dump($foo);' string(1) "1" # Passing an empty value part will set the configuration directive to "" php -d max_execution_time= -r '$foo = ini_get("max_execution_time"); var_dump($foo);' string(0) "" # The configuration directive will be set to anything passed after the '=' character $ php -d max_execution_time=20 -r '$foo = ini_get("max_execution_time"); var_dump($foo);' string(2) "20" $ php -d max_execution_time=doesntmakesense -r '$foo = ini_get("max_execution_time"); var_dump($foo);' string(15) "doesntmakesense"

Activate the extended information mode, to be used by a debugger/profiler.

Parse and execute the specified file. The -f is optional and may be omitted — providing just the filename to execute is sufficient.

Provides a convenient way to perform only a syntax check on the given PHP code. On success, the text No syntax errors detected in is written to standard output and the shell return code is 0 . On failure, the text Errors parsing in addition to the internal parser error message is written to standard output and the shell return code is set to -1 .

This option won’t find fatal errors (like undefined functions). Use the -f to test for fatal errors too.

Note:

This option does not work together with the -r option.

Example #1 Printing built in (and loaded) PHP and Zend modules

$ php -m [PHP Modules] xml tokenizer standard session posix pcre overload mysql mbstring ctype [Zend Modules]

Allows execution of PHP included directly on the command line. The PHP start and end tags ( ) are not needed and will cause a parse error if present.

Note:

Care must be taken when using this form of PHP not to collide with command line variable substitution done by the shell.

Example #2 Getting a syntax error when using double quotes

$ php -r "$foo = get_defined_constants();" PHP Parse error: syntax error, unexpected '=' in Command line code on line 1 Parse error: syntax error, unexpected '=' in Command line code on line 1

The problem here is that sh/bash performs variable substitution even when using double quotes » . Since the variable $foo is unlikely to be defined, it expands to nothing which results in the code passed to PHP for execution actually reading:

$ php -r " = get_defined_constants();"

The correct way would be to use single quotes ‘ . Variables in single-quoted strings are not expanded by sh/bash.

Example #3 Using single quotes to prevent the shell’s variable substitution

$ php -r '$foo = get_defined_constants(); var_dump($foo);' array(370) < ["E_ERROR"]=>int(1) ["E_WARNING"]=> int(2) ["E_PARSE"]=> int(4) ["E_NOTICE"]=> int(8) ["E_CORE_ERROR"]=> [. ]

If using a shell other than sh/bash, further issues might be experienced — if appropriate, a bug report should be opened at » https://github.com/php/php-src/issues. It is still easy to run into trouble when trying to use variables (shell or PHP) in command-line code, or using backslashes for escaping, so take great care when doing so. You have been warned!

Note:

-r is available in the CLI SAPI , but not in the CGI SAPI .

Note:

This option is only intended for very basic code, so some configuration directives (such as auto_prepend_file and auto_append_file) are ignored in this mode.

PHP code to execute before processing stdin.

PHP code to execute for every input line.

There are two special variables available in this mode: $argn and $argi . $argn will contain the line PHP is processing at that moment, while $argi will contain the line number.

PHP file to execute for every input line.

PHP code to execute after processing the input.

Example #4 Using the -B, -R and -E options to count the number of lines of a project.

$ find my_proj | php -B '$l=0;' -R '$l += count(@file($argn));' -E 'echo "Total Lines: $l\n";' Total Lines: 37328

Display colour syntax highlighted source.

This option uses the internal mechanism to parse the file and writes an HTML highlighted version of it to standard output. Note that all it does is generate a block of [. ] HTML tags, no HTML headers.

Note:

This option does not work together with the -r option.

Example #5 Using -v to get the SAPI name and the version of PHP and Zend

$ php -v PHP 5.3.1 (cli) (built: Dec 11 2009 19:55:07) Copyright (c) 1997-2009 The PHP Group Zend Engine v2.3.0, Copyright (c) 1998-2009 Zend Technologies

Display source with comments and whitespace stripped.

Note:

This option does not work together with the -r option.

Load Zend extension. If only a filename is given, PHP tries to load this extension from the current default library path on your system (usually /etc/ld.so.conf on Linux systems, for example). Passing a filename with an absolute path will not use the system’s library search path. A relative filename including directory information will tell PHP to try loading the extension relative to the current directory.

Show configuration file names and scanned directories.

Example #6 —ini example

$ php --ini Configuration File (php.ini) Path: /usr/dev/php/5.2/lib Loaded Configuration File: /usr/dev/php/5.2/lib/php.ini Scan for additional .ini files in: (none) Additional .ini files parsed: (none)

Show information about the given function or class method (e.g. number and name of the parameters).

This option is only available if PHP was compiled with Reflection support.

Example #7 basic —rf usage

$ php --rf var_dump Function [ public function var_dump ] < - Parameters [2] < Parameter #0 [ $var ] Parameter #1 [ $. ] > >

Show information about the given class (list of constants, properties and methods).

This option is only available if PHP was compiled with Reflection support.

Example #8 —rc example

$ php --rc Directory Class [ class Directory ] < - Constants [0] < >- Static properties [0] < >- Static methods [0] < >- Properties [0] < >- Methods [3] < Method [ public method close ] < >Method [ public method rewind ] < >Method [ public method read ] < >> >

Show information about the given extension (list of php.ini options, defined functions, constants and classes).

This option is only available if PHP was compiled with Reflection support.

Example #9 —re example

$ php --re json Extension [ extension #19 json version 1.2.1 ] < - Functions < Function [ function json_encode ] < >Function [ function json_decode ] < >> >

Show the configuration information for the given Zend extension (the same information that is returned by phpinfo() ).

Show the configuration information for the given extension (the same information that is returned by phpinfo() ). The core configuration information is available using «main» as extension name.

Example #10 —ri example

$ php --ri date date date/time support => enabled "Olson" Timezone Database Version => 2009.20 Timezone Database => internal Default timezone => Europe/Oslo Directive => Local Value => Master Value date.timezone => Europe/Oslo => Europe/Oslo date.default_latitude => 59.930972 => 59.930972 date.default_longitude => 10.776699 => 10.776699 date.sunset_zenith => 90.583333 => 90.583333 date.sunrise_zenith => 90.583333 => 90.583333

Note:

Options -rBRFEH , —ini and —r[fcezi] are available only in CLI .

Источник

Два типа расширений PHP. Zend extension VS PHP module

image

PHP module – оно же обычное расширение PHP
К этому типу относится подавляющее число расширений в PHP. Все то, что подключается в php.ini с помощью инструкции extension=some_library.so — это они и есть.

Zend extension
Расширений такого типа крайне мало, однако они ничуть не менее востребованы.

В статье я обзорно, совсем по верхам, расскажу, чем же эти два типа расширений отличаются.

С точки зрения конечного пользователя.

Отличаются только способом подключения.
Обычные расширения подключаются через php.ini с помощью инструкции:
extension=some_extension.so
Расширения zend с помощью:
zend_extension=some_extension.so .

Если хочется подключить через аргумент командной строки, то, для обычных:
php -d extension=/path/extension.so
А для расширений zend:
php -z /path/zend_extension.so

Однако под капотом они очень разные.

Тут очень подходит аналогия с бензиновым и дизельным двигателем. Для пользователя вся разница заключается только в типе топлива, которое он заливает в бак, но по факту это две совершенно разных конструкции, с разными принципами работы и со своими плюсами и минусами.

С точки зрения решаемых задач

Стандартные расширения, в подавляющем числе случаев, используются для расширения функциональных возможностей языка, таких как добавления новых классов, функций, констант и т.д. Крайне редко используются для решения других задач. Например, PECL расширение Vulcan Logic Disassembler(vld) позволяет посмотреть сгенерированный opcode для скрипта.

Расширения zend используются в случаях, когда нужно максимально глубоко залезть внутрь виртуальной машины. Например для отладки или профилирования скрипта, либо для изменения логики работы PHP.

С точки зрения разработчика, который раньше не писал расширений для PHP и вдруг сподобился

Написание обычных расширений хорошо документировано и описано во множестве статей. Для них даже есть инструмент генерации скелета проекта, включенный в исходные коды PHP.

В случае с Zend extension ничего этого нет. Хороших статей практически нет. Плохих тоже. Будьте готовы к длительному и вдумчивому изучению исходных кодов как самого PHP, так и немногих существующих расширений данного типа.

С точки зрения жизненного цикла

К сожалению, тут не обойтись без кода на С, поскольку жизненный цикл расширения целиком и полностью является отражением определяющей его структуры. (Структуры привожу в сокращенном виде. Только то, что необходимо в рамках статьи)

Стандартное расширение задается структурой _zend_module_entry (описывается в zend_module.h )

struct _zend_module_entry < /* skipped */ int (*module_startup_func)(INIT_FUNC_ARGS); /* MINIT() */ int (*module_shutdown_func)(SHUTDOWN_FUNC_ARGS); /* MSHUTDOWN() */ int (*request_startup_func)(INIT_FUNC_ARGS); /* RINIT() */ int (*request_shutdown_func)(SHUTDOWN_FUNC_ARGS); /* RSHUTDOWN() */ void (*info_func)(ZEND_MODULE_INFO_FUNC_ARGS); /* PHPINFO() */ /* skipped */ void (*globals_ctor)(void *global); /* GINIT() */ void (*globals_dtor)(void *global); /* GSHUTDOWN */ int (*post_deactivate_func)(void); /* PRSHUTDOWN() */ /* skipped */ >;

Расширение Zend задается структурой _zend_extension (описывается в zend_extensions.h )

А вот теперь уже можно показывать картинку с жизненным циклом.

image

Бонус. Гибридные расширения

Да. Такая возможность есть.

Зачем оно может понадобиться?

  1. Вам нужен полный контроль, предоставляемый расширением zend и, помимо этого, хочется зарегистрировать новые функции.
  2. Вам, зачем-то, понадобилось использовать вообще все возможные хуки.
  3. Вам необходимо управлять порядком загрузки своего расширения. К примеру надо загрузиться не раньше загрузки OPCache .

Источник

Оцените статью