cft

Writing Nested Functions - JS & PHP

Nesting a Function means having multiple functions called child functions within a particular Function called the parent function.


user

Simon Ugorji

2 years ago | 6 min read

Today I will show you how you can write and access nested functions in both JavaScript and PHP.

Nesting a Function means having multiple functions called child functions within a particular Function called the parent function.

In order to Nest a Function, you must have a parent function, then child function(s) within it.

Let's Start off with JavaScript

Let's assume that we are building a simple calculator that will return the child functions ( plus ) and ** ( minus )**.

The Plus will simply add up the numbers provided and the minus will simply subtract the numbers provided.

Parent Function

We will start off by declaring the parent function as calculate() to accept 2 parameters which are (x, y).

function calculate(x, y){
/**
* @calculate: Returns child functions
* @ x : Value 1 of type int
* @ y : Value 2 of type int
**/

}

Now let's declare a local variable to hold the parameters x and y, then multiply it by (1) to make sure that we are really working with Numbers.

function calculate(x, y){
/**
* @calculate: Returns child functions
* @ x : Value 1 of type int
* @ y : Value 2 of type int
**/

let a = x * 1;
let b = y * 1;

}

Child Function

Let's declare a child function that will return the sum of the values. We will call this function add() then we will pass in the parameters (a, b).

function calculate(x, y){
/**
* @calculate: Returns child functions
* @ x : Value 1 of type int
* @ y : Value 2 of type int
**/

let a = x * 1;
let b = y * 1;

function add(a, b){
return ( a + b );
}
}

Now, let's test out this simple function by returning an object with a custom name and our child function as its value.

function calculate(x, y){
/**
* @calculate: Returns child functions
* @ x : Value 1 of type int
* @ y : Value 2 of type int
**/

let a = x * 1;
let b = y * 1;

function sum(a, b){
return ( a + b );
}

return {
plus : sum
}
}

This practically means that anytime we access the returned value plus, our calculate function will execute its child function sum().

Let's declare a variable that will hold our function and its properties.

var calculate = calculate();

Now I will show you two ways to access our function properties. Think of it like you're accessing an object.

We will access plus property and pass in parameters ( 5, 5 ) to return the sum of the two values.

  • The dot notation

var calculate = calculate();
var sum = calculate.plus(5, 5);
console.log(sum);

  • Using square brackets

This method is quite tricky. But in PHP, this is also one of the ways I could think of that can be used to access nested functions.

Using this method means that you have to pass in the property that you're trying to access as a string, then output the result by passing in your parameters.

Sounds confusing right? Take a look at the code below.

var calculate = calculate();
var sum = calculate['plus'];
console.log(sum( 5, 5 ));

We have assigned the function property plus to the variable sum, passing no parameters.

Now we output the value from the sum variable by passing values (5, 5).

As you can see, it's the same Output.

More Child Functions

Let's add 2 more child functions to subtract our values or multiply them.

function calculate(x, y){
/**
* @calculate: Returns child functions
* @ x : Value 1 of type int
* @ y : Value 2 of type int
**/

let a = x * 1;
let b = y * 1;

function sum(a, b){
return ( a + b );
}
function subtract(a, b){
return ( a - b );
}
function multiply(a, b){
return ( a * b );
}

return {
plus : sum,
minus : subtract,
times : multiply
}
}
var calculate = calculate();
var sum = calculate.plus(5, 5);
var subtract = calculate.minus(5, 5);
var multiply = calculate.times(5, 5);

console.log('sum = '+sum);
console.log('minus = '+subtract);
console.log('times = '+ multiply);

Now, this is the exact output that we need.

That's it for JavaScript Nested Functions.

PHP

Well, the process is still the same in PHP except that you can't access the property of a nested function using the dot notation.

This is because the dot notation known as the concatenator, is used to join two strings or variables together.

We still have 2 available ways of accessing our Nested Function.

  • Using a global Variable

We will declare a global variable to hold our function and its properties, then pass in parameters at the same time, then we will use the square brackets to access our variable properties.

Note that we will also pass in the parameters to the child functions in our return value.

function calc($x, $y){
$a = $x;
$b = $y;
function sum($a, $b){
return ($a + $b);
};

$retval = [
"sum" => sum($x, $y) //pass in the param for child function sum()
];

return $retval;
}
//Bind function to variable
$calcs = calc(1,2);

//Return all properties as an array
//var_dump($calcs);

//access the sum property
echo ($calcs['sum']);

Now, this is the exact output that we expect.

  • Using a Variable then calling its properties like they were all declared as functions.

Before I show you this method, Let us add some child functions.

function calc($x, $y){
$a = $x;
$b = $y;
function sum($a, $b){
return ($a + $b);
}

function subtract($a, $b){
return ($a - $b);
}

$retval = [
"sum" => sum($x, $y),
"minus" => subtract($x, $y)
];

return $retval;
}

Now because we are returning our child functions with parameters passed directly to it, we can call the child functions directly anywhere on our page.

function calc($x, $y){
$a = $x;
$b = $y;
function sum($a, $b){
return ($a + $b);
}

function subtract($a, $b){
return ($a - $b);
}

$retval = [
"sum" => sum($x, $y),
"minus" => subtract($x, $y)
];

return $retval;
}
//add a dummy value to prevent argument count error
$calcs = calc(1, 1);

//add child function
echo ("20 + 10 child function = ".sum(20, 10)) .'<br>';

//subtract child function
echo ("20 - 10 child function = ".subtract(20, 10));

This is once again the output that we need.

I hope that at this point, we've understood what Nested functions are, and how to write them in both JavaScript and PHP.

Thank You!

Upvote


user
Created by

Simon Ugorji

Backend Developer | PHP | JS


people
Post

Upvote

Downvote

Comment

Bookmark

Share


Related Articles