Pass data to function php

PHP Functions

PHP has more than 1000 built-in functions, and in addition you can create your own custom functions.

PHP Built-in Functions

PHP has over 1000 built-in functions that can be called directly, from within a script, to perform a specific task.

Please check out our PHP reference for a complete overview of the PHP built-in functions.

PHP User Defined Functions

Besides the built-in PHP functions, it is possible to create your own functions.

  • A function is a block of statements that can be used repeatedly in a program.
  • A function will not execute automatically when a page loads.
  • A function will be executed by a call to the function.

Create a User Defined Function in PHP

A user-defined function declaration starts with the word function :

Syntax

Note: A function name must start with a letter or an underscore. Function names are NOT case-sensitive.

Tip: Give the function a name that reflects what the function does!

In the example below, we create a function named «writeMsg()». The opening curly brace ( < ) indicates the beginning of the function code, and the closing curly brace ( >) indicates the end of the function. The function outputs «Hello world!». To call the function, just write its name followed by brackets ():

Example

writeMsg(); // call the function
?>

PHP Function Arguments

Information can be passed to functions through arguments. An argument is just like a variable.

Arguments are specified after the function name, inside the parentheses. You can add as many arguments as you want, just separate them with a comma.

The following example has a function with one argument ($fname). When the familyName() function is called, we also pass along a name (e.g. Jani), and the name is used inside the function, which outputs several different first names, but an equal last name:

Example

familyName(«Jani»);
familyName(«Hege»);
familyName(«Stale»);
familyName(«Kai Jim»);
familyName(«Borge»);
?>

The following example has a function with two arguments ($fname and $year):

Example

function familyName($fname, $year) echo «$fname Refsnes. Born in $year
«;
>

familyName(«Hege», «1975»);
familyName(«Stale», «1978»);
familyName(«Kai Jim», «1983»);
?>

PHP is a Loosely Typed Language

In the example above, notice that we did not have to tell PHP which data type the variable is.

PHP automatically associates a data type to the variable, depending on its value. Since the data types are not set in a strict sense, you can do things like adding a string to an integer without causing an error.

In PHP 7, type declarations were added. This gives us an option to specify the expected data type when declaring a function, and by adding the strict declaration, it will throw a «Fatal Error» if the data type mismatches.

In the following example we try to send both a number and a string to the function without using strict :

Example

function addNumbers(int $a, int $b) return $a + $b;
>
echo addNumbers(5, «5 days»);
// since strict is NOT enabled «5 days» is changed to int(5), and it will return 10
?>

Читайте также:  Www chaynikam info cpu specif html

To specify strict we need to set declare(strict_types=1); . This must be on the very first line of the PHP file.

In the following example we try to send both a number and a string to the function, but here we have added the strict declaration:

Example

function addNumbers(int $a, int $b) return $a + $b;
>
echo addNumbers(5, «5 days»);
// since strict is enabled and «5 days» is not an integer, an error will be thrown
?>

The strict declaration forces things to be used in the intended way.

PHP Default Argument Value

The following example shows how to use a default parameter. If we call the function setHeight() without arguments it takes the default value as argument:

Example

setHeight(350);
setHeight(); // will use the default value of 50
setHeight(135);
setHeight(80);
?>

PHP Functions — Returning values

To let a function return a value, use the return statement:

Example

PHP Return Type Declarations

PHP 7 also supports Type Declarations for the return statement. Like with the type declaration for function arguments, by enabling the strict requirement, it will throw a «Fatal Error» on a type mismatch.

To declare a type for the function return, add a colon ( : ) and the type right before the opening curly ( < )bracket when declaring the function.

In the following example we specify the return type for the function:

Example

You can specify a different return type, than the argument types, but make sure the return is the correct type:

Example

Passing Arguments by Reference

In PHP, arguments are usually passed by value, which means that a copy of the value is used in the function and the variable that was passed into the function cannot be changed.

When a function argument is passed by reference, changes to the argument also change the variable that was passed in. To turn a function argument into a reference, the & operator is used:

Example

Use a pass-by-reference argument to update a variable:

Источник

Pass data to function php

To experiment on performance of pass-by-reference and pass-by-value, I used this script. Conclusions are below.

#!/usr/bin/php
function sum ( $array , $max ) < //For Reference, use: "&$array"
$sum = 0 ;
for ( $i = 0 ; $i < 2 ; $i ++)#$array[$i]++; //Uncomment this line to modify the array within the function.
$sum += $array [ $i ];
>
return ( $sum );
>

$max = 1E7 //10 M data points.
$data = range ( 0 , $max , 1 );

$start = microtime ( true );
for ( $x = 0 ; $x < 100 ; $x ++)$sum = sum ( $data , $max );
>
$end = microtime ( true );
echo «Time: » .( $end — $start ). » s\n» ;

/* Run times:
# PASS BY MODIFIED? Time
— ——- ——— —-
1 value no 56 us
2 reference no 58 us

3 valuue yes 129 s
4 reference yes 66 us

1. PHP is already smart about zero-copy / copy-on-write. A function call does NOT copy the data unless it needs to; the data is
only copied on write. That’s why #1 and #2 take similar times, whereas #3 takes 2 million times longer than #4.
[You never need to use &$array to ask the compiler to do a zero-copy optimisation; it can work that out for itself.]

2. You do use &$array to tell the compiler «it is OK for the function to over-write my argument in place, I don’t need the original
any more.» This can make a huge difference to performance when we have large amounts of memory to copy.
(This is the only way it is done in C, arrays are always passed as pointers)

Читайте также:  Перевод числа в четверичную систему python

3. The other use of & is as a way to specify where data should be *returned*. (e.g. as used by exec() ).
(This is a C-like way of passing pointers for outputs, whereas PHP functions normally return complex types, or multiple answers
in an array)

5. Sometimes, pass by reference could be at the choice of the caller, NOT the function definitition. PHP doesn’t allow it, but it
would be meaningful for the caller to decide to pass data in as a reference. i.e. «I’m done with the variable, it’s OK to stomp
on it in memory».
*/
?>

Источник

passing data into a function

The problem is that the $phrases arrays aren’t being sent to the function I can include the file in the function itself but I know that’s the wrong way to do it. I think I need to use $global just not sure how.

1 Answer 1

Method 1: Pass $phrases, $tts_phrases as parameters

function return_phrase(array $phrases, array $ttphrases, $phrase_name="", $fallback="",$default ="text") < $next= (isset($default) && $default =="mp3") ? 'text' : 'mp3'; if(isset($tts_phrases[$default][$phrase_name]))< return $phrases[$default][$phrase_name]); >else if(isset($tts_phrases[$next][$phrase_name])) < return $phrases[$next][$phrase_name]); >else < return $fallback; >> 

Method 2: Make $phrases, $tts_phrases global (bad!)

function return_phrase($phrase_name="", $fallback="",$default ="text") < global $phrases, $tts_phrases; $next= (isset($default) && $default =="mp3") ? 'text' : 'mp3'; if(isset($tts_phrases[$default][$phrase_name]))< return $phrases[$default][$phrase_name]); >else if(isset($tts_phrases[$next][$phrase_name])) < return $phrases[$next][$phrase_name]); >else < return $fallback; >> 

Using global variables is a quick and easy fix, but once your application gets larger they become very hard to keep track of. For example, take this legacy code snippet that I have to deal with at work:

Any time I am looking at one of the pages that just pulls one of those variables out of thin air, I have to Ctrl+F the whole project and make sure that every little change hasn’t messed up the whole app. When you keep your variables in local scope, you know exactly what you are changing.

Источник

passing POST array to php function

Please note that register_globals (not register_global ) is not required to use $HTTP_POST_VARS (the non-superglobal and deprecated brother to $_POST )! See here: de.php.net/manual/en/ini.core.php#ini.register-globals

Right, that was my other guess as to it’s use. Couldn’t remember exactly, but I knew Aif was wrong. At any rate, register_globals is bad! Beyond that, it’s deprecated. Don’t use it!

3 Answers 3

Yes. If you are going to name the local variable $_POST though, don’t bother. $_POST is a ‘superglobal’, a global that doesn’t require the global keyword to use it outside normal scope. Your above function would work without the parameter on it.

NOTE You cannot use any superglobal (i.e. $_POST ) as a function argument in PHP 5.4 or later. It will generate a Fatal error

You can actually pass $_POST to any function which takes in an array.

function process(array $request) < >process($_POST); process($_GET); 

The $_POST -array is an array like every other array in PHP (besides being a so-called superglobal), so you can pass it as a function parameter, pass it around and even change it (even though this might not be wise in most situations).

Regarding your code, I’d change it a bit to make it more clear:

PostInfo($_POST); function PostInfo($postVars) < $item1 = $postVars[0]; $item2 = $postVars[1]; $item3 = $postVars[2]; //do something return $result; >

This will visibly separate the function argument from the $_POST superglobal. Another option would be to simple remove the function argument and rely on the superglobal-abilities of $_POST :

PostInfo(); function PostInfo() < $item1 = $_POST[0]; $item2 = $_POST[1]; $item3 = $_POST[2]; //do something return $result; >

Источник

Читайте также:  Метод центральных прямоугольников python

Pass data to function php

Published on October 29, 2013

PHP version 5.3 introduced a new feature called anonymous functions, or lambda functions. You may have come across them in other languages such as C# or Ruby. They allow for greater flexibility and offer a clean, expressive syntax.

Anonymous functions are passed as arguments to other functions, and in this context they are usually referred to as callbacks. Let’s look at a really simple example of this using PHP’s array_filter function:

 
1
2
3// This is just creating a really simple array.
4$myArray = array('a', 'really', 'simple', 'array');
5
6// Call the array_filter function using our really simple array and a
7// custom callback.
8$myNewArray = array_filter($myArray, function($value)
9 return $value != 'a';
10>);

If we run the above code our really simple array will only have three values: ‘really’, ‘simple’, ‘array’ . This is because in our callback (anonymous function) we said that if the $value != ‘a’ to return true (when $value is ‘a’ our expression returns false). When we return true from our anonymous function, the array_filter function will keep the value in the array, and if we return false from our anonymous function the value is not added to our new array.

For the purpose of this post, let’s say we wanted to store the value to check against in its own variable like this:

 
1
2
3// This is just creating a really simple array.
4$myArray = array('a', 'really', 'simple', 'array');
5
6
7$valueToCheckAgainst = 'a';
8
9// Call the array_filter function using our really simple array and a
10// custom callback.
11$myNewArray = array_filter($myArray, function($value)
12 return $value != $valueToCheckAgainst;
13>);

If we try to run this we code we will get an error similar to this:

Notice: Undefined variable: valueToCheckAgainst

But how come? We obviously declared the variable and we gave it a value! Surely PHP must be playing tricks on us!

Drama aside, the reason PHP gives us the error is because anonymous functions execute in a different scope than our regular code so our anonymous function cannot ‘see’ any of the variables we’ve declared outside of the anonymous function. To resolve this, we must use the use keyword. That looks like this:

 
1
2
3// This is just creating a really simple array.
4$myArray = array('a', 'really', 'simple', 'array');
5
6
7$valueToCheckAgainst = 'a';
8
9// Call the array_filter function using our really simple array and a
10// custom callback.
11$myNewArray = array_filter($myArray, function($value) use ($valueToCheckAgainst)
12 return $value != $valueToCheckAgainst;
13>);

That’s all we have to do to make a variable available to our anonymous function when we cannot alter the number of parameters or anonymous function can have.

Tip: you can pass multiple variables to your anonymous function with the use keyword by separating them with a comma:

 
1
2
3// This is just creating a really simple array.
4$myArray = array('a', 'really', 'simple', 'array');
5
6
7$valueToCheckAgainst = 'a';
8$valueToCheckAgainst2 = 'b';
9$valueToCheckAgainst3 = 'c';
10
11// Call the array_filter function using our really simple array and a
12// custom callback.
13$myNewArray = array_filter($myArray, function($value) use ($valueToCheckAgainst, $valueToCheckAgainst2, $valueToCheckAgainst3)
14 return in_array($value, [
15 $valueToCheckAgainst, $valueToCheckAgainst2, $valueToCheckAgainst3
16 ]);
17>);

Источник

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