search
HomeBackend DevelopmentPHP TutorialExplanation on PHP custom functions and internal functions

1. Variable scope
is also called the scope of a variable. The scope of a variable is the context in which it is defined (also its effective scope).
Most PHP variables have only one single scope. This single scope The scope span also includes files introduced by include and require.

global keyword: You can use the global keyword inside the function to access global variables

You can also use $GLOBALS and other super-global arrays

For example:

$str = 'xxxx';
function test(){
//方法一:
global $str;
echo $str;
//方法二
//echo $GLOBALS['str']
}

2. Static variables
Static variables only exist in the local function domain, but their values ​​will not disappear when the program execution leaves this scope

static keyword
Only Initialize once
Need to assign a value during initialization
The value will be retained each time the function is executed
static modified variables are local and only valid within the function
The number of calls to the function can be recorded, so that it can be used in a certain Terminate recursion under these conditions

2.1, global variables, static variables

<?php /**
 * 写出如下程序的输出结果:
 * <?php
 *
 * $count = 5;
 * function get_count()
 * {
 *     static $count;
 *     return $count++;
 * }
 * echo $count;
 * ++$count;
 *
 * echo get_count();
 * echo get_count();
 * 
 * ?>
 *
 */

$count = 5;
function get_count()
{
    static $count;
    return $count++;
}


echo $count;//5
++$count;

//这里还涉及到运算符:递减NULL值没有效果,但是递增NULL值为1
echo get_count();//null,第一次定义的static $count,内容为null,现返回内容null,再null++,结果为1
echo get_count();//1,static $count = 1,现返回1,再递增


2.2, function transfer

<?php $var1 = 5;
$var2 = 10;


function foo(&$my_var)
{
    global $var1;
    $var1 += 2;
    $var2 = 4;
    $my_var += 3;
    return $var2;
}


$my_var = 5;
echo foo($my_var). "\n";//4
echo $my_var. "\n";//8
echo $var1;//7
echo $var2;//10
$bar = &#39;foo&#39;;
$my_var = 10;
echo $bar($my_var). "\n";//4


2.3, The reference of the function returns

从函数返回一个引用,必须在函数声明和指派返回值给一个变量都是用引用运算符&
<?php function &myFunc()
{
    static $b = 10;
    return $b;
}

echo myFunc();//10

$a = &myFunc();//此步a直接引用到b的地址

$a = 100;//修改a的值,相当于修改b的值

echo myFunc();//100 ,因为b是一个静态变量,该值会保留


3. Import of external files
If the path name is given, search according to the path, otherwise search from include_path
If there is no include_path, Then search from the directory where the calling script file is located and the current working directory

When a file is included, the code contained in it inherits the variable scope of the line where the include is located

If there is none of the above If found, the following error or warning will be reported
require and require_once: When it fails, a fatal level error will be generated and the program will stop running.
include and include_once: Only a warning level error is generated when it fails, and the program continues to run.

The only difference between the two is that when the included file code already exists, it is no longer included

4. System built-in functions
4.1, time and date function
date() //Format Timestamp
strtotime() //Parse the English text date and time into a Unix timestamp
mktime() //Integer Unix timestamp
time() //Get the current time timestamp
microtime () //Get milliseconds
date_default_timezone_set() //Set the default time zone

4.2, ip processing function
long2ip: Convert the long integer into a dotted Internet standard format address in string form ( IPV4)
ip2long: Convert the IPV4 string Internet protocol into a long integer number

4.3. Printing function
echo()
can output multiple values ​​at one time, between multiple values Separate with commas. echo is a language construct, not a real function, so it cannot be used as part of an expression.

print(): The value of a simple type variable (such as int, string)
The function print() prints a value (its parameter) and returns true if the string is successfully displayed, otherwise it returns false.

print_r(): You can print out the value of complex type variables (such as arrays, objects)
You can simply print out strings and numbers, while arrays are in the form of an enclosed list of keys and values. Displayed and starts with Array. But the results of print_r() outputting Boolean values ​​and NULL are meaningless, because they all print "\n". Therefore, using the var_dump() function is more suitable for debugging.
Print human-readable information about the variable. If a string, integer or float is given, the variable value itself will be printed. If an array is given, the keys and elements will be displayed in a certain format. object is similar to an array. Remember, print_r() will move the array pointer to the end. Use reset() to return the pointer to the beginning.

var_dump()
This function displays structural information about one or more expressions, including the type and value of the expression. Arrays will expand values ​​recursively, showing their structure through indentation.
Determine the type and length of a variable, and output the value of the variable. If the variable has a value, the value of the variable is output and the data type is returned. This function displays structural information about one or more expressions, including the expression's type and value. The array will recursively expand the values, showing its structure through indentation.

var_export(): Output or return a string representation of a variable
This function returns structural information about the variable passed to the function

You can pass the second The parameter is set to TRUE, thereby returning the representation of the variable. It returns valid PHP code.

var_dump和print_r的区别:
var_dump返回表达式的类型与值而print_r仅返回结果,相比调试代码使用var_dump更便于阅读。

var_dump和var_export的区别:
var_export() 函数返回关于传递给该函数的变量的结构信息,是合法的 PHP 代码,可以通过将函数的第二个参数设置为 TRUE,从而返回变量的表示
var_dump() 打印变量的相关信息

printf():根据格式进行输出
sprintf():根据格式转换字符串,并返回


4.4, serialize and deserialize unserialize

<?php    
$a = array(&#39;a&#39; => 'Apple' ,'b' => 'banana' , 'c' => 'Coconut');   

//序列化数组   
$s = serialize($a);  
echo $s;  
//输出结果:a:3:{s:1:"a";s:5:"Apple";s:1:"b";s:6:"banana";s:1:"c";s:7:"Coconut";}   
echo '<br><br>';  
  
//反序列化  
$o = unserialize($s);  
print_r($o);  
//输出结果 Array ( [a] => Apple [b] => banana [c] => Coconut )


4.5, json_encode and json_decode

<?php  
$a = array(&#39;a&#39; => 'Apple' ,'b' => 'banana' , 'c' => 'Coconut');
//序列化数组
$s = json_encode($a);
echo $s;
//输出结果:{"a":"Apple","b":"banana","c":"Coconut"}
echo '<br><br>';

//反序列化
$o = json_decode($s);

在上面的例子中,json_encode输出长度比上个例子中serialize输出长度显然要短


4.6. String function
php Summary of string usage


4.7.Array function
php array operation

Related recommendations:

php custom function records log

PHP custom function determines which submission method

The built-in function in JS and How to use custom functions

The above is the detailed content of Explanation on PHP custom functions and internal functions. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP Performance Tuning for High Traffic WebsitesPHP Performance Tuning for High Traffic WebsitesMay 14, 2025 am 12:13 AM

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

Dependency Injection in PHP: Code Examples for BeginnersDependency Injection in PHP: Code Examples for BeginnersMay 14, 2025 am 12:08 AM

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

PHP Performance: is it possible to optimize the application?PHP Performance: is it possible to optimize the application?May 14, 2025 am 12:04 AM

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

PHP Performance Optimization: The Ultimate GuidePHP Performance Optimization: The Ultimate GuideMay 14, 2025 am 12:02 AM

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use