Custom function in php application

In this tutorial, you will learn how to write custom function in php, and php objects and properties in object oriented programming, here we see how to write a custom function that returns any data type we want!

function functionName($p1, $p2)
{
    echo "write any code here \n";
    return $result;
}

While writing code, just try to follow single responsibility principal, your code will be more easily maintainable, simply write separate function for each functionality like getDislikesCount(id) , getLikeCount(id) etc.

Then call whichever function you need in your above code, thus code will be reusable, clean and easy to debug.

The idea is to write clean code, how you can simplify the code in php program.

<?php
function getDislikesCount($ttsongID) {
$counttldislikes = mysqli_query($db_conx, "SELECT * FROM `songdislikes` WHERE `dislikes`='" . $ttsongID . "'");
$tlnumberdislikes = mysqli_num_rows($counttldislikes);
	
return $tlnumberdislikes;
}
?>

Above function will return a number, you can write custom function returning any other data type like string, date or an array.

Now let's call the above function.

<?php 
getDislikesCount($ttsongID);
?>

The advantage of writing custom function in php application development, that you can develop a reusable code, which is more easy to maintain and enhance when your application grows up, function looks more meaningful and easy to understand the flow of code.

Php custom function with multiple parameters

We can write custom function with any number of parameters, with some return type or just not returning any data, for example writing some log details, etc.

  
<?php
function getResult($parameter1, $parameter2, /*...,*/ $parameter3)
{
    echo "here is my result.\n";

    return $result;
}
?>

Instead of passing each individual parameter in your custom function, you can also pass an php class object, which can help reducing code and easy to enhance in future.

You may be interested in following code

 
PHP Custom Function
Learn php programming, php web development with free tutorials
Other Popular Tutorials
PHP Examples | Join PHP Online Course