Table of Contents
Beniao learns php (5) declaration and use of functions
Home Backend Development PHP Tutorial Benniao learns PHP (5) Declaration and use of functions_PHP tutorial

Benniao learns PHP (5) Declaration and use of functions_PHP tutorial

Jul 13, 2016 am 10:21 AM
function

Beniao learns php (5) declaration and use of functions

1. Function declaration

<?php

	/**
	 * function 函数名(参数1, 参数2.... ){
	 *  	函数体;
	 *  	返回值;
	 * }
	 */
	
	$sum = sum(3, 4);
	echo $sum;
	
	function sum($x, $y){
		$sum = 0;
		$sum = $x * $x + $y + $y;
		return $sum;
	}
?>
Copy after login

2. Scope of variables

Local variables: Variables declared in a function are local variables and can only be used within your own function .
Global variables: Variables declared outside a function are global variables. They can be used after the variable is declared until the end of the entire script, including in functions and { }.

2.1 Knowledge point: PHP variables cannot be distinguished whether they are declared or used

<?php
	$a = 10;
	function demo($a){
		$a += 10;
		echo $a . &#39;<br>&#39;;
	}
	demo($a);
	echo $a;
	// 结果: 20, 10
	// PHP的变量分不出 $a 是声明还是使用
?>
Copy after login
2.2 Knowledge point: When using global variables in a function, you must use the global keyword. The variable after declaring global is the global variable

<?php
	$a = 10;
	
	function demo() {
		global $a;
		$a += 10;
		echo $a . " demo <br>";
	}
	
	function test() {
		global $a;
		$a += 5;
		echo $a . "test <br>";
	}
	
	echo $a . " ----<br>";  // 10 ----
	demo();                 // 20 demo 
	echo $a . " !!!!<br>";  // 20 !!!!
	demo();                 // 30 demo 
	echo $a . " @@@@<br>";  // 30 @@@@
	test();                 // 35 test 
	echo $a . " ####<br>";  // 35 ####
?>
Copy after login

Static variables: can only be declared in functions (classes) and cannot be declared globally. Use the static keyword to modify before the variable.

2.3 Knowledge point: Static variables are stored in static code blocks. Its value can be shared between multiple calls of a function, but it is only declared to memory when the function is called for the first time

When called in the future, it will not be declared but used directly (similar to Java).

<?php
   function test(){
	   static $a = 0;
	   $a++;
	   echo $a."<br>";
   }

  test(); // 1
  test(); // 2
  test(); // 3
?>
Copy after login

3. Variable function

In fact, this is very similar to JS, for example: define $var = hello, the next time you use $var(), you will look for the function hello() with the same name as the variable value

<?php
	  function one($a, $b){
	  	return $a + $b;
	  }
	
	  function two($a, $b){
	 	return $a * $a + $b * $b; 
	  }
	
	  function three($a, $b){
	  	return $a * $a * $a + $b * $b * $b;
	  }
	
	  //$var = one;
	  //$var = "two";
	  $var = three;
	
	  echo "结果:".$var(3, 4)."<br>"; // 91
?>
Copy after login

4. System function

4.1 Regular functions
bool copy (string source, string dest)

4.2 With mixed, mixed means that any type of data can be transmitted
bool chown (string filename, mixed user)

4.3 Function with & parameter, indicating reference assignment. This parameter cannot pass a value, only a variable can be passed, and then the function changes the value of the variable,

When we use this variable, the value also changes (the same as passing references in Java)

bool arsort (array &array [, int sort_flags])
<?php
	$arr=array(1, 9, 5, 8, 3, 4);
	sort($arr);
	print_r($arr);
?>
Copy after login
4.4 Default function, a function with [], indicates that this parameter is optional. If you pass a value, the value you passed will be used. If no value is passed, the default value will be used
bool arsort (array &array [, int sort_flags])
<?php
	function demo($a=1, $b=20, $c){
		echo "### $a ### $b ### $c ###<br>";
	}	
	demo(8,9);
?>
Copy after login
4.5 Parameter function with..., ... means that any number of parameters can be passed
int array_unshift (array &array, mixed var [, mixed ...])

<?php
	function demo(){
		  $sum = 0;
		  for($i = 0; $i < func_num_args(); $i++){
		  	  $sum += func_get_arg($i);
		  }
		  return $sum;
	 }
	 
	echo demo(1, 2, 3, 4, 5, 6, 7, 8, 9);
?>
Copy after login

4.6 Callback function with callback, that is, when calling this function, we need to pass in a function (function name, function name string)
array array_filter (array input [, callback callback])

<?php
   function demo($n){
	   	if($n % 2== 0){
			return true;
	   	}else{
			return false;
	   	}
   }
   
   $a = array(1, 2, -3, 4, -5, 6, -7, 8, 9);
   print_r(array_filter($a, demo));  // Array ( [1] => 2 [3] => 4 [5] => 6 [7] => 8 ) 
?>
Copy after login


www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/854421.htmlTechArticleStupid Bird Learning PHP (5) Declaration and Use of Functions 1. Declaration of functions 2. Scope of variables local variables : Variables declared in a function are local variables and can only be used within your own function...
Statement of this Website
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

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 Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Tips for dynamically creating new functions in golang functions Tips for dynamically creating new functions in golang functions Apr 25, 2024 pm 02:39 PM

Go language provides two dynamic function creation technologies: closure and reflection. closures allow access to variables within the closure scope, and reflection can create new functions using the FuncOf function. These technologies are useful in customizing HTTP routers, implementing highly customizable systems, and building pluggable components.

Considerations for parameter order in C++ function naming Considerations for parameter order in C++ function naming Apr 24, 2024 pm 04:21 PM

In C++ function naming, it is crucial to consider parameter order to improve readability, reduce errors, and facilitate refactoring. Common parameter order conventions include: action-object, object-action, semantic meaning, and standard library compliance. The optimal order depends on the purpose of the function, parameter types, potential confusion, and language conventions.

Complete collection of excel function formulas Complete collection of excel function formulas May 07, 2024 pm 12:04 PM

1. The SUM function is used to sum the numbers in a column or a group of cells, for example: =SUM(A1:J10). 2. The AVERAGE function is used to calculate the average of the numbers in a column or a group of cells, for example: =AVERAGE(A1:A10). 3. COUNT function, used to count the number of numbers or text in a column or a group of cells, for example: =COUNT(A1:A10) 4. IF function, used to make logical judgments based on specified conditions and return the corresponding result.

How to write efficient and maintainable functions in Java? How to write efficient and maintainable functions in Java? Apr 24, 2024 am 11:33 AM

The key to writing efficient and maintainable Java functions is: keep it simple. Use meaningful naming. Handle special situations. Use appropriate visibility.

Comparison of the advantages and disadvantages of C++ function default parameters and variable parameters Comparison of the advantages and disadvantages of C++ function default parameters and variable parameters Apr 21, 2024 am 10:21 AM

The advantages of default parameters in C++ functions include simplifying calls, enhancing readability, and avoiding errors. The disadvantages are limited flexibility and naming restrictions. Advantages of variadic parameters include unlimited flexibility and dynamic binding. Disadvantages include greater complexity, implicit type conversions, and difficulty in debugging.

What are the benefits of C++ functions returning reference types? What are the benefits of C++ functions returning reference types? Apr 20, 2024 pm 09:12 PM

The benefits of functions returning reference types in C++ include: Performance improvements: Passing by reference avoids object copying, thus saving memory and time. Direct modification: The caller can directly modify the returned reference object without reassigning it. Code simplicity: Passing by reference simplifies the code and requires no additional assignment operations.

What is the difference between custom PHP functions and predefined functions? What is the difference between custom PHP functions and predefined functions? Apr 22, 2024 pm 02:21 PM

The difference between custom PHP functions and predefined functions is: Scope: Custom functions are limited to the scope of their definition, while predefined functions are accessible throughout the script. How to define: Custom functions are defined using the function keyword, while predefined functions are defined by the PHP kernel. Parameter passing: Custom functions receive parameters, while predefined functions may not require parameters. Extensibility: Custom functions can be created as needed, while predefined functions are built-in and cannot be modified.

C++ Function Exception Advanced: Customized Error Handling C++ Function Exception Advanced: Customized Error Handling May 01, 2024 pm 06:39 PM

Exception handling in C++ can be enhanced through custom exception classes that provide specific error messages, contextual information, and perform custom actions based on the error type. Define an exception class inherited from std::exception to provide specific error information. Use the throw keyword to throw a custom exception. Use dynamic_cast in a try-catch block to convert the caught exception to a custom exception type. In the actual case, the open_file function throws a FileNotFoundException exception. Catching and handling the exception can provide a more specific error message.

See all articles