Php: Classes & Functions

Hi Experts,

I am a beginner-intermediate PHP developer... and for the life of me cant work out Why? How? When? to use functions and classes...

Could someone please simplify this
Thanks in advance
maccaj51Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Marco GasiFreelancerCommented:
Wow, what a question! We can't write a book here! ;-) Well, I suggest to let classes for another time: you can read some book about that:

PHP Object, Patterns and Practices (http://www.apress.com/9781590599099)
The PHP Anthology: 101 Essential Tips, Tricks & Hacks (http://www.sitepoint.com/books/phpant2/?historicredirect=phpant1)
PHP Master Write Cutting-Edge Code (http://www.sitepoint.com/books/phppro1/)

Come to the functions: you can use them every time a piece of code has to be repeated in a script or in an application. Consider this extremely stupid sample:

$length = 100 + 200;
$total = 40 + 32;
$something = $a + $b;
and so on...

Here you would have to use a function like this

function sum($a, $b){
  return $a + $b;
}

$length = sum(100, 200);
$total = sum(40, 32);
$something = sum($a, $b);

In this sample the advantage is no so clear, but consider if you have a bigger piece of code: enclosing it within a function will avoid you to write and rewrite it again and again. Not only: if you have your code in a function, you'll be able to change it once and have its result changed along all your application editing a single piece pf code and you'll don't risk to have to edit the same cvode again and again in different part of your application aand to forget to change it somewhere.

Hope this is clear enough. I suggest you another book: http://www.sitepoint.com/books/phpmysql4/ It will give you a good base to start understanding function's usefulness

Cheers
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
DerokorianCommented:
Another good example would be when building forms. Maybe you have a bunch of different forms but you always need to have a date input. Consider these functions:
<?php
function selectMonth($name,$select = 0,$glue = PHP_EOL) {
	$month = array('January','February','March','April','May','June','July','August','September','October','November','December');
	$return = array();
	$return[] = "<select name='$name'>";
	$return[] = "\t<option value='0'>Month</option>";
	for( $i=0;$i<=11;$i++) {
		$v = $i+1;
		$return[] = "\t<option value='$v'".($select==$v?" selected='selected'":'').">$month[$i]</option>";
	}
	$return[] = '</select>';
	return implode($glue,$return);
} // Function: selectMonth

function selectDay($name,$select = 0,$glue = PHP_EOL) {
	$return = array();
	$return[] = "<select name='$name'>";
	$return[] = "\t<option value='0'>Day</option>";
	for( $i=1; $i<32; $i++ ) {
	  $return[] = "\t<option value='$i'".($select==$i?" selected='selected'":'').">$i</option>";
	}
	$return[] = "</select>";
	return implode($glue,$return);
} // Function: selectDay

function selectYear($name,$select = 0,$glue = PHP_EOL) {
	$return = array();
	$return[] = "<select name='$name'>";
	$return[] = "\t<option value='0'>Year</option>\n";
	for( $i=-1; $i<100; $i++ ) {
		$year = date("Y")-$i;
		$return[] = "\t<option value='$year'".($select==$year?" selected='selected'":'').">$year</option>";
	}
	$return[] = "</select>";
	return implode($glue,$return);
} // Function: selectYear

Open in new window


Now when you are building your form you could do:
<label for="DOB">Date of Birth</label>
<?php echo selectDay('dob_day') . selectMonth('dob_month') . selectYear('dob_year'); ?>

Open in new window


and bam! you have all 3 drop downs created auto-magically! What if you had multiple dates needed in a form, you'd have to type out the content of those functions a number of times instead of simply changing the fieldname given to the function call.
0
Ray PaseurCommented:
Buy this book.
http://www.amazon.com/gp/product/143022925X/

After you have read the introductory parts and the first chapter, read every page linked from this page.
http://us3.php.net/manual/en/language.oop5.php

When to use classes?  Whenever you need to keep related code and related data together in one place.  Classes encapsulate the variable and function names, so there is much less risk of clobbering the work of someone else who is working on your project.  Here is an example of a class that creates a stopwatch object.  You can use it to time the execution of all or of several parts of your scripts.  A set of demonstration code is at the end.  Imagine trying to do something like that without object encapsulation!
<?php // RAY_class_Stopwatch.php
error_reporting(E_ALL);


// DEMONSTRATE A SCRIPT TIMER FOR ALL OR PART OF A SCRIPT PHP 5+
// MAN PAGE http://php.net/manual/en/function.microtime.php


class StopWatch
{
    protected $a; // START TIME
    protected $s; // STATUS - IF RUNNING
    protected $z; // STOP TIME

    public function __construct()
    {
        $this->a = array();
        $this->s = array();
        $this->z = array();
    }

    // A METHOD TO REMOVE A TIMER
    public function reset($name='TIMER')
    {
        // RESET ALL TIMERS
        if ($name == 'TIMER')
        {
            $this->__construct();
        }
        else
        {
            unset($this->a[$name]);
            unset($this->s[$name]);
            unset($this->z[$name]);
        }
    }

    // A METHOD TO CAPTURE THE START TIME
    public function start($name='TIMER')
    {
        $this->a[$name] = microtime(TRUE);
        $this->z[$name] = $this->a[$name];
        $this->s[$name] = 'RUNNING';
    }

    // A METHOD TO CAPTURE THE END TIME
    public function stop($name='TIMER')
    {
        $ret = NULL;

        // STOP ALL THE TIMERS
        if ($name == 'TIMER')
        {
            foreach ($this->a as $name => $start_time)
            {
                // IF THIS TIMER IS STILL RUNNING, STOP IT
                if ($this->s[$name])
                {
                    $this->s[$name] = FALSE;
                    $this->z[$name] = microtime(TRUE);
                }
            }
        }

        // STOP ONLY ONE OF THE TIMERS
        else
        {
            if ($this->s[$name])
            {
                $this->s[$name] = FALSE;
                $this->z[$name] = microtime(TRUE);
            }
            else
            {
                $ret .= "ERROR: CALL TO STOP() METHOD FOR '$name' IS NOT RUNNING";
            }
        }

        // RETURN AN ERROR MESSAGE, IF ANY
        return $ret;
    }

    // A METHOD TO READ OUT THE TIMER(S)
    public function readout($name='TIMER', $dec=3, $m=1000, $eol=PHP_EOL)
    {
        $str = NULL;

        // GET READOUTS FOR ALL THE TIMERS
        if ($name == 'TIMER')
        {
            foreach ($this->a as $name => $start_time)
            {
                $str .= $name;

                // IF THIS TIMER IS STILL RUNNING UPDATE THE END TIME
                if ($this->s[$name])
                {
                    $this->z[$name] = microtime(TRUE);
                    $str .= " RUNNING ";
                }
                else
                {
                    $str .= " STOPPED ";
                }

                // RETURN A DISPLAY STRING
                $lapse_time = $this->z[$name] - $start_time;
                $lapse_msec = $lapse_time * $m;
                $lapse_echo = number_format($lapse_msec, $dec);
                $str .= " $lapse_echo";
                $str .= $eol;
            }
            return $str;
        }

        // GET A READOUT FOR ONLY ONE TIMER
        else
        {
            $str .= $name;

            // IF THIS TIME IS STILL RUNNING, UPDATE THE END TIME
            if ($this->s[$name])
            {
                $this->z[$name] = microtime(TRUE);
                $str .= " RUNNING ";
            }
            else
            {
                $str .= " STOPPED ";
            }


            // RETURN A DISPLAY STRING
            $lapse_time = $this->z[$name] - $this->a[$name];
            $lapse_msec = $lapse_time * $m;
            $lapse_echo = number_format($lapse_msec, $dec);
            $str .= " $lapse_echo";
            $str .= $eol;
            return $str;
        }
    }
}



// DEMONSTRATE THE USE -- INSTANTIATE THE STOPWATCH OBJECT
$sw  = new Stopwatch;

// SET A STOPWATCH NAME THAT REFLECTS THE PARTS OF THE SCRIPT WE WANT TO TIME
$g_timer = 'GOOGLE TIMER';

// START A TIMER TO GET ELAPSED TIME FOR A CALL TO GOOGLE
$sw->start($g_timer);

// PERFORM SOME ACTIVITY THAT YOU WANT TO TIME (READS GOOGLE WEB PAGE)
$page = 'http://google.com';
$html = file_get_contents($page);

// GET A READOUT OF THE TIMER WHILE IT IS STILL RUNNING
echo nl2br($sw->readout($g_timer));
echo "<br/>" . PHP_EOL;

// PERFORM SOME OTHER ACTIVITY (READS GOOGLE WEB PAGE AGAIN)
$page = 'http://google.com';
$html = file_get_contents($page);

// STOP THE TIMER AND GET A READOUT WITH SHORT DECIMALS
$x = $sw->stop($g_timer);
echo nl2br($sw->readout($g_timer, 1));
echo "<br/>" . PHP_EOL;




// START A SECOND TIMER
$y_timer = 'YAHOO TIMER';
$sw->start($y_timer);

// PERFORM SOME OTHER ACTIVITY THAT YOU WANT TO TIME
$page = 'http://yahoo.com/';
$html = file_get_contents($page);

// REPORT THE STOPWATCHES CONTENT (ONE IS STOPPED AND ONE IS STILL RUNNING)
echo nl2br($sw->readout());
echo "<br/>" . PHP_EOL;

// SHOW THE OBJECT
echo "<pre>";
var_dump($sw);
echo "</pre>";

// STOP ALL OF THE STOPWATCHES
$sw->stop();

// REPORT THE STOPWATCHES CONTENT AGAIN
echo nl2br($sw->readout());
echo "<br/>" . PHP_EOL;

// SHOW THE OBJECT
echo "<pre>";
var_dump($sw);
echo "</pre>";



// TRY TO STOP A TIMER THAT IS NOT RUNNING
$x = $sw->stop($g_timer);
var_dump($x);
echo "<br/>" . PHP_EOL;
echo "<br/>" . PHP_EOL;



// START THIS TIMER OVER AGAIN
$sw->start($y_timer);

// PERFORM SOME OTHER ACTIVITY THAT YOU WANT TO TIME
$page = 'http://weather.yahoo.com/';
$html = file_get_contents($page);

// REPORT THE STOPWATCHES CONTENT
echo nl2br($sw->readout());
echo "<br/>" . PHP_EOL;

// SHOW THE OBJECT
echo "<pre>";
var_dump($sw);
echo "</pre>";



// REMOVE ONE OF THE STOPWATCHES
$sw->reset($g_timer);

// REPORT THE STOPWATCHES CONTENT
echo nl2br($sw->readout());
echo "<br/>" . PHP_EOL;

// SHOW THE OBJECT
echo "<pre>";
var_dump($sw);
echo "</pre>";



// REMOVE ALL OF THE STOPWATCHES
$sw->reset();
echo "ALL STOPWATCHES HAVE BEEN REMOVED";

// REPORT THE STOPWATCHES CONTENT (SHOWS NOTHING)
echo nl2br($sw->readout());

// SHOW THE OBJECT
echo "<pre>";
var_dump($sw);
echo "</pre>";

Open in new window

0
Slick812Commented:
Greetings  maccaj51, , , When someone does code work, they write letters and numbers to try and tell a code translator what to have the computer do in machine code (assembly instructions), since the computer CPU does not under stand words or numbers that we type. So your code has to be readable, clear to you, and organized so you can understand what you want it to do, get an end result. You asked = "Why? When? to use functions and classes"  for me this is mostly a way to organize code into groupings that make it easy to find and correct things that need to be changed as you add to your code, or need to change something that does not work. If you only have a couple of hundred lines of code, you can look through it all in not much time, but if you have 20,000 lines of code, you absolutely need a way to group and organize code that is similar into functions and classes. For me placing code into a Class does NOT make it better code, or have it do a better job. But if I use a class wrapper to package code together, then it offers me a way to find errors or changes in database by going to the database class, or looking for changes in the display or DHTML view, by going to the display class. Classes have several methods like __get() that can offer you some extended functioning if you learn those. It is not the easiest thing to learn and use classes, but it does pay off for your time and effort. You may should ask less general questions, I can not begin to tell you how to use them, , there are thousands of PHP tutorials about PHP classes-functions on the web.
0
maccaj51Author Commented:
Considering my lack of knowledge I can only thank you all for all your inputs and distribute the points accordingly.

Thanks Experts!!!!
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
PHP

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.