Jump to content

Recommended Posts

Hello there,

I have been learning PHP and MySQL for the last few years in the direct version, by this I mean on directly on the page rather than in functions. Now I find myself using the same code over again by copying and pasting from different projects and would like to create a function library that I can include in my page and call when needed. Although I'm finding it hard to understand how to handle errors and returning values from these functions.

 

For example I use the following code for validating forms, it goes through each of the expected POST and if any required POST is missing then it pushes an error. How wud I make this a function?

 

$expected = array('title', 'headline', 'description');
$required = array('title', 'description');
$missing = array();
// process the $_POST variables
foreach ($_POST as $key => $value) {
  $temp = is_array($value) ? $value : trim($value);
  if (empty($temp) && in_array($key, $required)) {
    array_push($missing, $key);
  }
  elseif (in_array($key, $expected)) {
    ${$key} = $temp;
  }
}

if (empty($missing)) {
//Do Something
}

 

Another example of code I use for validating dates for database input. How would you make this a function?

 

if (!is_numeric($d) || !is_numeric($y)) {
    $message[] = 'Please use numbers only for day and year';
}
elseif (($d <1 || $d > 31) || ($y < 1000 || $y > 9999)) {
    $message[] = 'Please use numbers within the correct range for day and year';
}
elseif (!checkdate($m,$d,$y)) {
    $message[] = 'You have used an invalid date';
}
else {
    $d = $d < 10 ? '0'.$d : $d;
    $date = "$y-$m-$d";
}

 

Any help would be much appreciated.

Regards

Link to comment
https://forums.phpfreaks.com/topic/206190-help-with-php-functions/
Share on other sites

Hi

 

I would honestly have to say functions and classes are very simple and funcdamental aspects of programming let alone PHP itself. Things you need to know to progress and write good applications.

 

My advice here would be to read and fully understand Object oriented programming

 

http://www.php.net/manual/en/language.functions.php

http://www.php.net/manual/en/language.oop5.php

 

 

I have redone your second example into a function below:

But do note that i havn't edited your code much but really just wrapped it in a function.

 

You need to read up on this stuff though.

 

To call this function, e.g.

 

print validate(02, 02, 1988);

 

 function validate($d, $m, $y){
        //set up an errlog array to be returned
        $message = array();
                //check numbers are numeric
            if (!is_numeric($d) || !is_numeric($y)) {
                $message[] = 'Please use numbers only for day and year';
                return $message;//error
            }
                //check numbers are between certain range
            elseif (($d <1 || $d > 31) || ($y < 1000 || $y > 9999)) {
                $message[] = 'Please use numbers within the correct range for day and year';
                return $message;//error
            }
                //check for valid date type
            elseif (!checkdate($m,$d,$y)) {
                $message[] = 'You have used an invalid date';
                return $message;//error
            }
            else {
                $d = $d < 10 ? '0'.$d : $d;
                $date = "$y-$m-$d";
                return $date;//returns date when validated
                exit();
            }
    }

 

 

 

Hope this helps

OOP should be a long term goal.  And, you're not going to learn OOP by merely reading syntax.  Stuffing a bunch of similar functions in a class is not OOP.

 

There's an art to writing good functions.  Unfortunately, it can only come with practice.  Just remember two things: functions are used to both reduce repeated code and to abstract code.  You should strive to keep your main code as readable as possible.  It should be free from as many bits of detail not directly related to whatever the main code should be doing as possible.  Look at PHP's built-in functions - you probably don't care, and wouldn't want to see, what something like mysql_query or include looks like under the hood, or exactly how they do what they do.  The same approach should be taken with custom functions.

 

So, some key thoughts when writing a function:

 

1. What should it do?

2. What kind of information will it need to complete its task (argument list - NEVER use the 'global' keyword)?

3. What should it return once it finishes doing its job ('nothing' is a valid answer)?

4. How can I make it as abstract as possible, being useful in as many situations as possible?

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.