All posts tagged PHP

Writing Functions In PHP – Flexibility

In our last example, we created say_hello() function which is something that has the ability to take a variable or an argument passed into it ($word), and we passed a string to it. If you missed the first tutorial, I recommend you read through that before starting this one.

Passing A Variable Into A Function.

Our previous example, we managed to pass a simple string into a function like so:

<html>
<head>
<title>Writing Functions In PHP - Flexibility</title>
</head>
<body>
<?php
    function say_hello($word){
        echo &quot;Hello {$word}!&quot;;
    }
    say_hello(&quot;Everyone&quot;); /* passing a string value into the function */
?>
</body>
</html>

It should make perfect sense to you that we can also pass a variable into a function. We do that by defining a variable and assigning a value to it. Lets take our previous function for this example.

<html>
<head>
<title>Writing Functions In PHP - Flexibility</title>
</head>
<body>
<?php
    function say_hello($word){
        echo &quot;Hello {$word}!<br>&quot;;
    }
    say_hello(&quot;Everyone&quot;); /* passing a string value into the function */

    $name = &quot;Monie&quot;; /* declare a variable and assign a value to it */
    say_hello($name); /* passing a variable into the function */
?>
</body>
</html>

What we are dong here is passing in a variable which is just a reference to the string into the function. So this will do what we’ve expected, it will reuse our say_hello() function and echo out “Hello Monie!”

Flexible Function With More Arguments

We’ve talked about arguments in our last tutorial, the benefit of having them is that it makes our function more flexible. We can actually make our functions even more flexible if we need to. Let me describe with an example.

<html>
<head>
<title>Writing Functions In PHP - Flexibility</title>
</head>
<body>
<?php
/* declaring our first function */
    function say_hello($word){
        echo &quot;Hello {$word}!<br>&quot;;
    }
    say_hello(&quot;Everyone&quot;); /* passing a string value into the function */

    $name = &quot;Monie&quot;; /* declare a variable and assign a value to it */
    say_hello($name); /* passing a variable into the function */

/* declaring our second function */
    function say_hello2($greeting, $person, $punct){
        echo $greeting .&quot;, &quot;. $person . $punct . &quot;<br>&quot;;
    }
    say_hello2(&quot;Greetings&quot;, $name, &quot;!&quot;); /* calling out the function */
?>
</body>
</html>

Output:
Hello Everyone!
Hello Monie!
Greetings, Monie!

As you can see, we have three different arguments defined to the function, “$greeting”, “$person” and “$punct”. When we call the function, we actually need to pass three arguments to the function as well. This is the most important feature of a function. We always need to call them with the exact same number of arguments that we’ve defined them with. Any less than that will return an error.

So we’ve made our function even more flexible by using more arguments. It’s up to you to determine what needs to be flexible and what doesn’t. After all, having all this complex customized function isn’t necessarily a good thing for you. That might be a real pain for you. It might be a lot better to let your function do some of the work and know how to make an assumption. It is what we call an Error Resistant Function. Sure, it would be a more complex flexible function but fortunately I will teach you how later on in this tutorial series.

Function With Returning Values

Most of the time, we will need this kind of function when we need to get a value or a result out of a function so that we can keep using it and keep working with it other that just displaying them with an echo statement. Consider this example:

We are trying to count how much money a person get for his overtime work. Each month, a person may or may not be working overtime. That’s why the total hours of overtime is set to a variable and not included in the function. The calculation will be done outside of the function or perhaps be sent to another function as an argument or variable. That means we need to get the value out of the function, which is the value of the person’s hourly pay salary, and them multiply it (another function) with the total number of overtime hours the person has.

Salary: $2000
Days of work in a month: 24 days
Total hours of work in a day: 8 hours
Total hours of overtime: Variable
Overtime rate: 1.5

To get yourself clear with our example in calculating the person’s overtime, here is the formula that I’ll be using.

(($salary / $month / $day) x $rate) x Total hours of overtime

<html>
<head>
<title>Writing Functions In PHP - Flexibility</title>
</head>
<body>
<?php
/* declaring our third function */
    function overtime($salary, $month, $day, $rate){
        $hourly_pay = ($salary / $month / $day) * $rate;
        echo $hourly_pay;
    }
    overtime(2000,24,8,1.5); /* passing four arguments into the function */
?>
</body>
</html>

In the above function, there is now a way for us to manipulate the value from inside the function and then use it outside of the function. It just displays the $hourly_pay value to us but we need to multiply it with the total hours of overtime to get the exact figure of what we are trying to archieve here.

So how can we return or send the value out of the function so that we can use them once the function has finished execution?  Join me on the next article to learn more about function with it’s capabilities for returning values.

Elements of PHP

What is PHP?

PHP is a scripting language used widely on the Web. With it, you can query other servers, create and process HTML pages and forms, open and write to files on your server, and perform many other essential server-side web development tasks.

Coding in PHP isn’t so different from coding in other procedural languages like C or Pascal, so whatever experience you have in that type of language will carry over to your PHP coding.

Some aspects of coding in PHP might require a slight change of how you think about programming, especially if you’ve never coded for server-side deployment before. For one thing, realize that you never interact with a PHP program while it’s running; instead, you only see the results of the program after it’s already run.

For example, you don’t use PHP to display a prompt with a message box that requests a user to enter her name. Client-side (i.e. JavaScript) apps take care of those tasks. Working through your first few PHP scripts will give you a better sense of the possible applications of this language.

Preparing to code

Your environment for coding PHP applications should ideally contain these tools: an IDE (integrated development environment) for writing and debugging PHP scripts; a simulated server for testing deployment of the scripts; and a reference source listing the detailed parameters needed for all PHP functions.

You can get the last of those features easily by surfing to PHP.net, the home page of the PHP development. All documentation for the PHP language is there. The docs include sample code, links to relevant resources, and contributed comments from PHP users, whose real-world experiences in PHP can make the difference between code that works and doesn’t work.

Integrated development environment

It’s possible to code PHP scripts in a plain text editor, but your development time will be much shorter and your development experience will be much happier, if you instead type your code within an integrated development environment (IDE).

A PHP IDE will point out syntax errors as soon as you make them, so you’re not wasting time hunting down such errors after you’ve uploaded a script to your server. An IDE will also clean (“tidy”) and format your code, so all the braces and parentheses line up nicely. If you’ve ever tried fixing unmatched parentheses errors using a plain text editor, you know how vital this feature is.

An IDE will also have a feature equivalent to Microsoft’s Intellisense, which displays pop-up menus that list the parameters and description of the PHP function you’re currently typing. This feature deletes the need for constant switching back and forth between your browser and development windows to consult the PHP API.

At least two organizations offer free IDEs for PHP: NetBeans.org and Eclipse.org.

The PHP runtime environment

Since PHP runs on a server, getting a simulated server for your development environment will help you see how your PHP script runs when you deploy it on the production server. You could install just the server software on your hard drive, but your workflow will be smoother if you integrate the installation with your IDE. The help pages for the NetBeans IDE have detailed instructions on installing an implementation of Apache server, and configuring it to work with NetBeans. Find the makers of this Apache implementation here.

Basic output

Create your first PHP program by pasting the following code into your IDE.

<?php
echo &quot;I like to go moshing with dolphins a-sloshing and swim between their fins.&quot;
?>

Save the file with any appropriate filename, though be sure it ends with the extension “.php.” Upload the saved file to your server, then request its URL in your Web browser. Unless you’ve made a syntax error, you’ll see the text in the quotes output to the screen.

Exploring the code

We’ll look at how the code in this script works. But first, keep in mind that PHP scripts must end with the .PHP, .PHP4 or .PHP5 file extension. If you request a page with PHP code from your browser, and that page has a different extension from the ones just mentioned, the server simply won’t execute your script.

The script itself begins and ends with tags that mark the text inside them as PHP code:

<?php

And

?>

The PHP interpreter on your server can’t “see” your code unless it’s in these tags. But, realize that these tags can show up in several places within your script. Try this script to see this:

<html>
	<body>
	<?php
		echo &quot;I like to go moshing with dolphins a-sloshing ...&quot;;
	?>
	and swim
	<?php
		echo &quot; between their fins.&quot;;
	?>
	</body>
</html>

Continue learning PHP’s elements in part 2 of this article.

Writing Functions In PHP – Introduction

The real power of PHP comes from its functions. If you’re looking for a way to save time when you program, look no further. Functions are going to allow us to be able to write code in one place and reuse it as many times as we want by just calling the function.

Creating functions lets you reuse code that you’ve used before without having to rewrite the whole thing again and again. When you understand and know how to use functions, you will be able to save a ton of time and write code in a more readable format!

User-Defined Functions

In PHP, there are more than 700 built-in functions. We are not going to use any of it in this tutorial but we are going to build our very own function.

Let’s take a look at the following typical structure of a function. When we want to declare a function, we would say function to tell PHP that we are defining a function, followed by the name of the function and any of the arguments that belong to the function.

<?php
   function name($arguments){
     statement;
}
?>

The name of a function can be just about anything you want. It can contain letters, numbers, underscores and dashes. It can’t contain any spaces. It must start with a letter or an underscore. Unlike string names, function names are going to be case insensitive which means that we can define a function with capital letters in it and actually called it with all lower case letters and it still finds the function and knows which one we meant. But that’s a bad programming practice and a bad habit.

So if you defined a function in capital letters, you call it with all capital letters. If you defined them with lowercase letters, you call it with lowercase letters. Let’s start defining our simple function.

Function Without Arguments

<html>
<head>
<title>Writing Functions In PHP - Introduction</title>
</head>
<body>
 <?php
 function say_hello(){
 echo &quot;Hello World!&quot;;
 }
 say_hello(); /* calling out the function */
 ?>
</body>
</html>

Output: Hello Word!

This simple function was executed by calling the function with say_hello(); echo out “Hello World!”.  Next we will look into another type of function with an argument passed to the function.

Function With Arguments

The reason we want to use arguments is that we want to give our functions flexibility. Flexibility is really a good and powerful thing for us because we can have code that we can reuse for different circumstances. Let’s update our first example with arguments.

<html>
<head>
<title>Writing Functions In PHP - Introduction</title>
</head>
<body>
 <?php
 function say_hello($word){
 echo &quot;Hello {$word}!&quot;;
 }
 say_hello(&quot;Everyone&quot;); /* calling out the function */
 ?>
</body>
</html>

Output:  Hello Everyone!

The same output will be printed out on your browser for this function. The only different thing about this function is its flexibility. This function has flexibility built into it because it can pass an argument and based on that argument, it can do different things in the code. This is what we called a dynamic function.

Defining Functions

Before we move on to a more advanced concept of functions, you need to know this basic idea of defining a function.

  • A function needs to be defined before we can call it.
  • You can’t define a function more than once.
  • You can call a function as many time as you like.
  • You can declare functions inside if else statement.
  • You can declare functions inside other functions.

What’s Next?

So far, you’ve learned how to define functions, how to call functions, how to pass some simple arguments into a function and how to develop a function that can be reusable.

In the next tutorial, I’ll be talking about more advanced tips that you can do with passing arguments into a function and some other things that we can do with functions. Click here for Part 2!