백엔드 개발 PHP 튜토리얼 PHP开发入门2>PHP扩展开发入门2 HELLO WORLD

PHP开发入门2>PHP扩展开发入门2 HELLO WORLD

Jun 20, 2016 pm 12:29 PM

    开发PHP扩展是一件很COOL的事情。不过难度自然要比开发PHP程序要复杂很多。毕竟是C语言。

    我打一开始学习编程就是用的最笨的办法。由于学习的不是计算机专业,所以学编程甚是头大。和大多数哥哥姐姐弟弟妹妹一样,我也是买了一本谭浩强的C语言,当然这个一方面是大家推荐,另外一方面谭老师的书在编程的书架上面放在了最醒目的位置,其他版本的在我们这个小地方也太难买到。

    学习编程,开始就是抄代码删代码,我觉得学这个开发扩展,开始不明白无所谓,先把编写的过程结构给弄清楚,这个应该比较简单,就是在什么位置,写什么代码,哪些可以修改,哪些不可以修改。熟悉过程了之后在去弄明白这段代码是什么意思,而且在删除代码的过程也就明白这段代码所起的作用。

    今天写个‘hello  world’,和所有的编程语言开始一样。如何写出来一个返回“hello world”的函数。

    首先,在终端中找到PHP源码的目录,然后在ext目录里,输入如下内容,其中"helloworld"为今天的函数名称

./ext_skel  --extname=helloworld
로그인 후 복사

接下来一起来见证奇迹的诞生,ext目录下有了helloworld目录。这个是没有任何功能的扩展,下面我们为其添加功能。

打开php_helloworld.h文件,在其中添加如下代码

PHP_FUNCTION(hellworld);
로그인 후 복사

添加后的文件如下

/*  +----------------------------------------------------------------------+  | PHP Version 5                                                        |  +----------------------------------------------------------------------+  | Copyright (c) 1997-2015 The PHP Group                                |  +----------------------------------------------------------------------+  | This source file is subject to version 3.01 of the PHP license,      |  | that is bundled with this package in the file LICENSE, and is        |  | available through the world-wide-web at the following url:           |  | http://www.php.net/license/3_01.txt                                  |  | If you did not receive a copy of the PHP license and are unable to   |  | obtain it through the world-wide-web, please send a note to          |  | license@php.net so we can mail you a copy immediately.               |  +----------------------------------------------------------------------+  | Author:                                                              |  +----------------------------------------------------------------------+*//* $Id$ */#ifndef PHP_HELLOWORLD_H#define PHP_HELLOWORLD_Hextern zend_module_entry helloworld_module_entry;#define phpext_helloworld_ptr &helloworld_module_entry#define PHP_HELLOWORLD_VERSION "0.1.0" /* Replace with version number for your extension */#ifdef PHP_WIN32#	define PHP_HELLOWORLD_API __declspec(dllexport)#elif defined(__GNUC__) && __GNUC__ >= 4#	define PHP_HELLOWORLD_API __attribute__ ((visibility("default")))#else#	define PHP_HELLOWORLD_API#endif#ifdef ZTS#include "TSRM.h"#endifPHP_MINIT_FUNCTION(helloworld);PHP_MSHUTDOWN_FUNCTION(helloworld);PHP_RINIT_FUNCTION(helloworld);PHP_RSHUTDOWN_FUNCTION(helloworld);PHP_MINFO_FUNCTION(helloworld);PHP_FUNCTION(confirm_helloworld_compiled);	/* For testing, remove later. *///-----------------------------------------------------------start---------------------------------------------//这里是我添加内容的开始PHP_FUNCTION(hellworld);//这里结束//-----------------------------------------------------end------------------------------------------------/*   	Declare any global variables you may need between the BEGIN	and END macros here:     ZEND_BEGIN_MODULE_GLOBALS(helloworld)	long  global_value;	char *global_string;ZEND_END_MODULE_GLOBALS(helloworld)*//* In every utility function you add that needs to use variables    in php_helloworld_globals, call TSRMLS_FETCH(); after declaring other    variables used by that function, or better yet, pass in TSRMLS_CC   after the last function argument and declare your utility function   with TSRMLS_DC after the last declared argument.  Always refer to   the globals in your function as HELLOWORLD_G(variable).  You are    encouraged to rename these macros something shorter, see   examples in any other php module directory.*/#ifdef ZTS#define HELLOWORLD_G(v) TSRMG(helloworld_globals_id, zend_helloworld_globals *, v)#else#define HELLOWORLD_G(v) (helloworld_globals.v)#endif#endif	/* PHP_HELLOWORLD_H *//* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: noet sw=4 ts=4 fdm=marker * vim<600: noet sw=4 ts=4 */
로그인 후 복사

下面打开helloworld.c,修改后如下

/*  +----------------------------------------------------------------------+  | PHP Version 5                                                        |  +----------------------------------------------------------------------+  | Copyright (c) 1997-2015 The PHP Group                                |  +----------------------------------------------------------------------+  | This source file is subject to version 3.01 of the PHP license,      |  | that is bundled with this package in the file LICENSE, and is        |  | available through the world-wide-web at the following url:           |  | http://www.php.net/license/3_01.txt                                  |  | If you did not receive a copy of the PHP license and are unable to   |  | obtain it through the world-wide-web, please send a note to          |  | license@php.net so we can mail you a copy immediately.               |  +----------------------------------------------------------------------+  | Author:                                                              |  +----------------------------------------------------------------------+*//* $Id$ */#ifdef HAVE_CONFIG_H#include "config.h"#endif#include "php.h"#include "php_ini.h"#include "ext/standard/info.h"#include "php_helloworld.h"/* If you declare any globals in php_helloworld.h uncomment this:ZEND_DECLARE_MODULE_GLOBALS(helloworld)*//* True global resources - no need for thread safety here */static int le_helloworld;/* {{{ helloworld_functions[] * * Every user visible function must have an entry in helloworld_functions[]. */const zend_function_entry helloworld_functions[] = {	PHP_FE(confirm_helloworld_compiled,	NULL)		/* For testing, remove later. */	PHP_FE(helloworld,	NULL)         /* 在这里添加代码 ,和上个文件中的函数名要一致*/	PHP_FE_END	/* Must be the last line in helloworld_functions[] */};/* }}} *//* {{{ helloworld_module_entry */zend_module_entry helloworld_module_entry = {#if ZEND_MODULE_API_NO >= 20010901	STANDARD_MODULE_HEADER,#endif	"helloworld",	helloworld_functions,	PHP_MINIT(helloworld),	PHP_MSHUTDOWN(helloworld),	PHP_RINIT(helloworld),		/* Replace with NULL if there's nothing to do at request start */	PHP_RSHUTDOWN(helloworld),	/* Replace with NULL if there's nothing to do at request end */	PHP_MINFO(helloworld),#if ZEND_MODULE_API_NO >= 20010901	PHP_HELLOWORLD_VERSION,#endif	STANDARD_MODULE_PROPERTIES};/* }}} */#ifdef COMPILE_DL_HELLOWORLDZEND_GET_MODULE(helloworld)#endif/* {{{ PHP_INI *//* Remove comments and fill if you need to have entries in php.iniPHP_INI_BEGIN()    STD_PHP_INI_ENTRY("helloworld.global_value",      "42", PHP_INI_ALL, OnUpdateLong, global_value, zend_helloworld_globals, helloworld_globals)    STD_PHP_INI_ENTRY("helloworld.global_string", "foobar", PHP_INI_ALL, OnUpdateString, global_string, zend_helloworld_globals, helloworld_globals)PHP_INI_END()*//* }}} *//* {{{ php_helloworld_init_globals *//* Uncomment this function if you have INI entriesstatic void php_helloworld_init_globals(zend_helloworld_globals *helloworld_globals){	helloworld_globals->global_value = 0;	helloworld_globals->global_string = NULL;}*//* }}} *//* {{{ PHP_MINIT_FUNCTION */PHP_MINIT_FUNCTION(helloworld){	/* If you have INI entries, uncomment these lines 	REGISTER_INI_ENTRIES();	*/	return SUCCESS;}/* }}} *//* {{{ PHP_MSHUTDOWN_FUNCTION */PHP_MSHUTDOWN_FUNCTION(helloworld){	/* uncomment this line if you have INI entries	UNREGISTER_INI_ENTRIES();	*/	return SUCCESS;}/* }}} *//* Remove if there's nothing to do at request start *//* {{{ PHP_RINIT_FUNCTION */PHP_RINIT_FUNCTION(helloworld){	return SUCCESS;}/* }}} *//* Remove if there's nothing to do at request end *//* {{{ PHP_RSHUTDOWN_FUNCTION */PHP_RSHUTDOWN_FUNCTION(helloworld){	return SUCCESS;}/* }}} *//* {{{ PHP_MINFO_FUNCTION */PHP_MINFO_FUNCTION(helloworld){	php_info_print_table_start();	php_info_print_table_header(2, "helloworld support", "enabled");	php_info_print_table_end();	/* Remove comments if you have entries in php.ini	DISPLAY_INI_ENTRIES();	*/}/* }}} *//* Remove the following function when you have successfully modified config.m4   so that your module can be compiled into PHP, it exists only for testing   purposes. *//* Every user-visible function in PHP should document itself in the source *//* {{{ proto string confirm_helloworld_compiled(string arg)   Return a string to confirm that the module is compiled in */PHP_FUNCTION(confirm_helloworld_compiled){	char *arg = NULL;	int arg_len, len;	char *strg;	if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &arg, &arg_len) == FAILURE) {		return;	}	len = spprintf(&strg, 0, "Congratulations! You have successfully modified ext/%.78s/config.m4. Module %.78s is now compiled into PHP.", "helloworld", arg);	RETURN_STRINGL(strg, len, 0);}/* }}} *//* The previous line is meant for vim and emacs, so it can correctly fold and    unfold functions in source code. See the corresponding marks just before    function definition, where the functions purpose is also documented. Please    follow this convention for the convenience of others editing your code.*//* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: noet sw=4 ts=4 fdm=marker * vim<600: noet sw=4 ts=4 */        /*  这里是功能 这个函数不接收参数,只有返回值。 */ PHP_FUNCTION(helloworld){	        int  len;	char *strg;		len = spprintf(&strg, 0, "%.78s", "helloworld");	RETURN_STRINGL(strg, len, 0);}
로그인 후 복사

在编译之前还需要修改一个文件,就是config.m4,将10、11、12三行最前面的dnl删除掉。这里删除这几个注释,是编译的时候让编译这个扩展,不然就忽略了。

dnl $Id$dnl config.m4 for extension helloworlddnl Comments in this file start with the string 'dnl'.dnl Remove where necessary. This file will not workdnl without editing.dnl If your extension references something external, use with:PHP_ARG_WITH(helloworld, for helloworld support,Make sure that the comment is aligned:[  --with-helloworld             Include helloworld support])dnl Otherwise use enable:dnl PHP_ARG_ENABLE(helloworld, whether to enable helloworld support,dnl Make sure that the comment is aligned:dnl [  --enable-helloworld           Enable helloworld support])if test "$PHP_HELLOWORLD" != "no"; then  dnl Write more examples of tests here...  dnl # --with-helloworld -> check with-path  dnl SEARCH_PATH="/usr/local /usr"     # you might want to change this  dnl SEARCH_FOR="/include/helloworld.h"  # you most likely want to change this  dnl if test -r $PHP_HELLOWORLD/$SEARCH_FOR; then # path given as parameter  dnl   HELLOWORLD_DIR=$PHP_HELLOWORLD  dnl else # search default path list  dnl   AC_MSG_CHECKING([for helloworld files in default path])  dnl   for i in $SEARCH_PATH ; do  dnl     if test -r $i/$SEARCH_FOR; then  dnl       HELLOWORLD_DIR=$i  dnl       AC_MSG_RESULT(found in $i)  dnl     fi  dnl   done  dnl fi  dnl  dnl if test -z "$HELLOWORLD_DIR"; then  dnl   AC_MSG_RESULT([not found])  dnl   AC_MSG_ERROR([Please reinstall the helloworld distribution])  dnl fi  dnl # --with-helloworld -> add include path  dnl PHP_ADD_INCLUDE($HELLOWORLD_DIR/include)  dnl # --with-helloworld -> check for lib and symbol presence  dnl LIBNAME=helloworld # you may want to change this  dnl LIBSYMBOL=helloworld # you most likely want to change this   dnl PHP_CHECK_LIBRARY($LIBNAME,$LIBSYMBOL,  dnl [  dnl   PHP_ADD_LIBRARY_WITH_PATH($LIBNAME, $HELLOWORLD_DIR/$PHP_LIBDIR, HELLOWORLD_SHARED_LIBADD)  dnl   AC_DEFINE(HAVE_HELLOWORLDLIB,1,[ ])  dnl ],[  dnl   AC_MSG_ERROR([wrong helloworld lib version or lib not found])  dnl ],[  dnl   -L$HELLOWORLD_DIR/$PHP_LIBDIR -lm  dnl ])  dnl  dnl PHP_SUBST(HELLOWORLD_SHARED_LIBADD)  PHP_NEW_EXTENSION(helloworld, helloworld.c, $ext_shared)fi
로그인 후 복사

到这里就大功告成了。这里开发工具已经做完了,剩下就是编译了。在该扩展目录下,依次执行如下命令

phpize
로그인 후 복사
./configure --withphp-config=php-config
로그인 후 복사
make
로그인 후 복사
sudo make install
로그인 후 복사

安装之后,需要在PHP.INI文件当中将扩展启用,在该文件最后一行添加

extension=helloworld.so
로그인 후 복사

接下来一起见证奇迹的诞生

<?phpecho helloworld();
로그인 후 복사

    这就是第一个PHP扩展。

본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

세션 납치는 어떻게 작동하며 PHP에서 어떻게 완화 할 수 있습니까? 세션 납치는 어떻게 작동하며 PHP에서 어떻게 완화 할 수 있습니까? Apr 06, 2025 am 12:02 AM

세션 납치는 다음 단계를 통해 달성 할 수 있습니다. 1. 세션 ID를 얻으십시오. 2. 세션 ID 사용, 3. 세션을 활성 상태로 유지하십시오. PHP에서 세션 납치를 방지하는 방법에는 다음이 포함됩니다. 1. 세션 _regenerate_id () 함수를 사용하여 세션 ID를 재생산합니다. 2. 데이터베이스를 통해 세션 데이터를 저장하십시오.

JWT (JSON Web Tokens) 및 PHP API의 사용 사례를 설명하십시오. JWT (JSON Web Tokens) 및 PHP API의 사용 사례를 설명하십시오. Apr 05, 2025 am 12:04 AM

JWT는 주로 신분증 인증 및 정보 교환을 위해 당사자간에 정보를 안전하게 전송하는 데 사용되는 JSON을 기반으로 한 개방형 표준입니다. 1. JWT는 헤더, 페이로드 및 서명의 세 부분으로 구성됩니다. 2. JWT의 작업 원칙에는 세 가지 단계가 포함됩니다. JWT 생성, JWT 확인 및 Parsing Payload. 3. PHP에서 인증에 JWT를 사용하면 JWT를 생성하고 확인할 수 있으며 사용자 역할 및 권한 정보가 고급 사용에 포함될 수 있습니다. 4. 일반적인 오류에는 서명 검증 실패, 토큰 만료 및 대형 페이로드가 포함됩니다. 디버깅 기술에는 디버깅 도구 및 로깅 사용이 포함됩니다. 5. 성능 최적화 및 모범 사례에는 적절한 시그니처 알고리즘 사용, 타당성 기간 설정 합리적,

확실한 원칙과 PHP 개발에 적용되는 방법을 설명하십시오. 확실한 원칙과 PHP 개발에 적용되는 방법을 설명하십시오. Apr 03, 2025 am 12:04 AM

PHP 개발에서 견고한 원칙의 적용에는 다음이 포함됩니다. 1. 단일 책임 원칙 (SRP) : 각 클래스는 하나의 기능 만 담당합니다. 2. Open and Close Principle (OCP) : 변경은 수정보다는 확장을 통해 달성됩니다. 3. Lisch의 대체 원칙 (LSP) : 서브 클래스는 프로그램 정확도에 영향을 미치지 않고 기본 클래스를 대체 할 수 있습니다. 4. 인터페이스 격리 원리 (ISP) : 의존성 및 사용되지 않은 방법을 피하기 위해 세밀한 인터페이스를 사용하십시오. 5. 의존성 반전 원리 (DIP) : 높고 낮은 수준의 모듈은 추상화에 의존하며 종속성 주입을 통해 구현됩니다.

시스템 재시작 후 UnixSocket의 권한을 자동으로 설정하는 방법은 무엇입니까? 시스템 재시작 후 UnixSocket의 권한을 자동으로 설정하는 방법은 무엇입니까? Mar 31, 2025 pm 11:54 PM

시스템이 다시 시작된 후 UnixSocket의 권한을 자동으로 설정하는 방법. 시스템이 다시 시작될 때마다 UnixSocket의 권한을 수정하려면 다음 명령을 실행해야합니다.

phpstorm에서 CLI 모드를 디버그하는 방법은 무엇입니까? phpstorm에서 CLI 모드를 디버그하는 방법은 무엇입니까? Apr 01, 2025 pm 02:57 PM

phpstorm에서 CLI 모드를 디버그하는 방법은 무엇입니까? PHPStorm으로 개발할 때 때때로 CLI (Command Line Interface) 모드에서 PHP를 디버그해야합니다 ...

PHP에서 늦은 정적 결합을 설명하십시오 (정적 : :). PHP에서 늦은 정적 결합을 설명하십시오 (정적 : :). Apr 03, 2025 am 12:04 AM

정적 바인딩 (정적 : :)는 PHP에서 늦은 정적 바인딩 (LSB)을 구현하여 클래스를 정의하는 대신 정적 컨텍스트에서 호출 클래스를 참조 할 수 있습니다. 1) 구문 분석 프로세스는 런타임에 수행됩니다. 2) 상속 관계에서 통화 클래스를 찾아보십시오. 3) 성능 오버 헤드를 가져올 수 있습니다.

PHP의 CURL 라이브러리를 사용하여 JSON 데이터가 포함 된 게시물 요청을 보내는 방법은 무엇입니까? PHP의 CURL 라이브러리를 사용하여 JSON 데이터가 포함 된 게시물 요청을 보내는 방법은 무엇입니까? Apr 01, 2025 pm 03:12 PM

PHP 개발에서 PHP의 CURL 라이브러리를 사용하여 JSON 데이터를 보내면 종종 외부 API와 상호 작용해야합니다. 일반적인 방법 중 하나는 컬 라이브러리를 사용하여 게시물을 보내는 것입니다 ...

See all articles