Category: Beginners’ Corner

2010-01-25

Beginners’ Corner: Variable Function Parameters

by Charles — Categories: Beginners' Corner, PHP — Tags: , , , Leave a comment

Sometimes when defining a function in PHP, you find that there may be cases where you do not want to specify all the possible parameters when calling it. This could be because you want it to use a default value, or that in certain cases it does not logically apply. If you find yourself in such a situation, probably the first thing you should do is ask yourself if two (or more) separate functions should be defined, instead. (Perhaps one function would call the other internally?)

Assuming you want to stick with one function, the most commonly used approach is to define a default value for one or more parameters in the parameter list. A parameter is assigned such a default value via the = operator, just as you would use it to assign a value in the function body.

function foo($bar='World') {
   echo "Hello, " . $bar;
}

When the function is called at run-time, if that parameter is not included in the call, then the default value will be used; otherwise the supplied value is used.

foo(); // Hello, World
foo('Joe'); // Hello, Joe

If you want your function definition to include both required and optional (default) parameters, the required parameters must come first in the list.

function foo($req1, $req2, $opt1='something', $opt2=null) { }

In the preceding example, the use of null can be convenient in that PHP treats a null variable as “not set” by the isset() function, allowing you to do something like:

function foo($bar=null) {
   if(isset($bar)) {
      echo $bar;
   } else {
      echo "Nobody home";
   }
}

Another approach which can be quite powerful in some ways, but for which I’ve really not run into much use myself, is the use of variable length argument lists. Essentially, the function prototype would have no parameters specified, then you use the func_num_args(), func_get_arg(), and/or func_get_args() functions to determine how many arguments were supplied and then decide what to do with them.

function test()
{
   $numArgs = func_num_args();
   switch($numArgs) {
      case 0:
         return false;
         break;
      case 1:
         echo "Hello, " . func_get_arg(0); // args start numbering at zero
         break;
      case 2:
         echo func_get_arg(0) . ", " . func_get_arg(1);
         break;
      default:
         echo "Here are the args:<br /><pre>";
         print_r(func_get_args());
         echo "</pre>";
   }
}

Lastly, another approach is to pass an associative array as the function parameter. You can then test for specific array keys to decide what to do.

function test($args)
{
   if (!is_array($args)) {
      user_error('Oops!');
      return false;
   }
   if (isset($args['name'])) {
      if (isset($args['verb'])) {
         echo $args['verb'] . ", " . $args['name'];
      } else {
         echo "Hello, " . $args['name'];
      }
   }
   return true;
}

A downside of this last method is that the function definition’s parameter list gives no clue by itself as to what array keys are expected/allowed. This can make it tricky to use and maintain, as the coder is at the mercy of the comments and documentation, or else is forced to read the entire function definition to figure out the possibilities.

2009-10-27

Beginners’ Corner: Learning Object-Oriented PHP

by Charles — Categories: Beginners' Corner, OOP, PHP — Tags: , , , 2 Comments

I often see PHP newbies (and even not-so-newbies) who are confused by the world of object-oriented programming (OOP). At least part of this confusion results from the vast majority of introductory books and tutorials for PHP beginning by teaching procedural programming techniques, treating OOP as an “advanced” subject with a chapter or two at the end. Thus the student is exposed to a bunch of new syntax concerning classes and objects with, at best, a very brief explanation as to “why” that syntax should be used. A purely object-oriented language such as Java or Ruby, on the other hand, will by its nature require that beginners’ resources more fully address the theory of OOP.

I am not going to claim to be an OOP guru, but I can point you to a few resources I have used to become reasonably proficient — but still learning! — with PHP classes and objects. First I would point you to an on-line tutorial at Sun.com: “Lesson: Object-Oriented Programming Concepts“. While the (relatively few) examples in these tutorials are in Java, the syntax is quite similar to that of PHP, and the lessons they illustrate are easily transferred to PHP. If you want to work with those examples yourself in PHP, I would recommend taking a look at a couple PHP tutorials at IBM.com: “Getting started with objects in PHP V5” and “Advanced PHP V5 objects“.

Once you’ve gotten past the basics, to see how things can work together as an OOP whole, I strongly suggest you get your hands on Matt Zandstra’s book, PHP Objects, Patterns, and Practice. Reading this book is what ultimately made objects “click” in my mind. After reading it I felt much more comfortable with the underlying concepts along with the specific techniques for applying them in my PHP projects.

2008-07-07

Beginners’ Corner: Avoid Bad Habits

by Charles — Categories: Beginners' Corner, PHP — Tags: , Leave a comment

This is the first “Beginners’ Corner” article, designed to help new PHP programmers in their quest to become veteran PHP programmers. In this initial installment we’ll look at a few things which are best avoided, but for various reasons often become habits of new PHP users who do not yet know better. Many of these may become habits simply because there are so many bad examples out there to learn from, often because they are dated and PHP has moved on in a manner which obsoletes them.

<?php Tags

The first bad habit to avoid is using <? instead of <?php or <?= instead of <?php echo. While saving those few keystrokes is a temptation to all of us lazy programmers, it is a potential problem should you need to run the script on a site where the short_open_tag option is disabled. One likely reason to have it disabled is in order to avoid confusion with <?xml tags in XML documents, and as XML is much more prevalent now than it was when PHP was created, you are more likely to find such configurations in use; so just get in the habit of typing those three extra characters and saving yourself a lot of aggravation in the future.

(more…)

2008-06-29

Beginners’ Corner: The Dreaded Blank Page

by Charles — Categories: Beginners' Corner, Debugging — Tags: , , 3 Comments

[2008/07/15: Added this to the "Beginners' Corner" category]

A common problem I see new PHP users running into is having a script output absolutely nothing: the dreaded “blank page” syndrome. This is normally due to a syntax error of some sort generating a fatal parse error. As this error is generated before any of the script is actually executed, none of the file’s output ever gets sent to the browser. If the current PHP environment on the server has display_errors turned off, then not even the error message generated by the parser gets displayed. Additionally, since no PHP commands actually get executed when there is a parse error, turning on display_errors within that script via the ini_set() function will make no difference.

The two usual approaches to debugging such problems are to either search the PHP or web server error logs to look for relevant error messages, or else to turn on display_errors, either globally in the php.ini file or at the directory level via a .htaccess file, assuming you are running under Apache and the necessary Apache settings are in effect to allow this. (A third alternative is to use an editor that has PHP syntax checking built in, such as PHPDesigner.)

If for some reason none of those approaches is practical for your situation, a simple way to have any  parse errors be displayed is to create a tiny wrapper script that includes the offending file:

<?php
ini_set('display_errors', 1);
error_reporting(E_ALL | E_STRICT);
include 'path/to/flawed/file.php';
?>

All you have to do is run this script in your browser, et voilà, your parse errors will now be displayed.

© 2012 PHP Musings All rights reserved - Wallow theme v0.46.4 by ([][]) TwoBeers - Powered by WordPress - Have fun!