My FTP Wrapper Class for PHP - Wrapping? Huh? (Page 2 of 7 )
Don’t be put off by the term wrapping. Wrapping just means that you are providing indirect access to a function. For example, here’s a wrapper for the echo function in PHP:
function outputText($TheText) { /* Could perform some error checking or formatting here */
// Output the text echo $TheText; }
If you don’t like the term “wrapper”, then you can also use “masking function” to name the process of wrapping a function.
“What’s the point of the example that you’ve just shown me?” I hear you ask. Yes, there isn’t much point wrapping a function like this, but let’s think about another situation. Let’s say that you want to use PHP’s ftp_connect, ftp_login, and ftp_chdir commands to connect to an FTP server, login with your credentials and then change into a specific directory, all from one class function...
Our First Wrapper Function Instead of calling all 3 functions separately, you could just wrap them into one function, which would handle each function and also the errors that each might produce, like this:
define("FT_DIRECTORY", 0); define("FT_FILE", 1);
class MY_FTP {
...
function Connect($Server, $User, $Password, $Directory, &$Err) { // Connect to the remote FTP server and then attempt // to change into a remote directory. Returns false // as well as a string in the $err reference if failed
// Attempt to connect to the remote server $this->__conn = @ftp_connect($Server);
if(!$this->__conn) { $Err = "Couldn't connect to server $Server"; return false; }
// Attempt to login to the remote server $this->__login = @ftp_login($this->__conn, $User, $Password);
if(!$this->__login) { $Err = "Couldn't login as user $User to $Server"; return false; }
// Attempt to change into the working directory $chDir = @ftp_chdir($this->__conn, $Directory);
if(!$chDir) { $Err = "Couldn't change into the $Directory directory"; return false; }
// Everything worked OK, return true return true; }
As you can see, this is much easier than handling the FTP functions manually. This is the first wrapper function in our FTP class, called MY_FTP. Basically, if anything fails, the Connect function returns false, and sets the value of the $Err variable to the reason why a connection couldn’t be made.
The $Err variable is passed to the Connect function as a reference. This is denoted by the preceding ampersand in the function header:
function Connect($Server, $User, $Password, $Directory, &$Err)
Instead of passing the value of a variable, a reference passes the address of the variable. For example:
<?php
$x = 10;
function doIt(&$Var) { $Var++; }
// This will output 11 because x is incremented by reference // in the doIt function doIt($x); echo $x;