Page 124 - Open Soource Technologies 304.indd
P. 124

Unit 7: Functions



            $var2 = $array[1];                                                                    Notes
            ...

            As previously mentioned, the indexes 0 and 1 returned by each() are used by the list() construct.
            You can probably already guess how the combination of list() and each() work. Consider the
            highlighted line from the previous $players traversal example:

            $players = array(“Peter”, “Barbara”, “Bill”, “Nancy”);

            reset($players);
            while (list($key, $val) = each($players)) {

            print “#$key = $val\n”;

            }
            What happens in the boldfaced line is that during every loop iteration, each() returns the current
            position’s key/value pair array, which, when examined with print_r(), is the following array:

            Array
            (

            [1] => Peter
            [value] => Peter

            [0] => 0

            [key] => 0
            )

            Then, the list() construct assigns the array’s offset 0 to $key and offset 1

            to $val.
            7.8.11 Additional Methods for Traversing Arrays

            You can use other functions to iterate over arrays including current() and next(). You shouldn’t
            use  them  because  they  are  confusing  and  are  legacy  functions.  In  addition,  some  standard
            functions allow all sorts of elegant ways of dealing with arrays such as array_walk(), which is
            covered in a later unit.

            7.9 Objects


            The main difference in OOP as opposed to functional programming is that the data and code are
            bundled together into one entity, which is known as an object. Object-oriented applications are
            usually split up into a number of objects that interact with each other. Each object is usually an
            entity of the problem, which is self-contained and has a bunch of properties and methods. The
            properties are the object’s data which basically means the variables that belong to the object.
            The methods if you are coming from a functional background are basically the functions that
            the object supports. Going one step further, the functionality that is intended for other objects
            to be accessed and used during interaction is called an object’ sinter face.



                                             LOVELY PROFESSIONAL UNIVERSITY                                   119
   119   120   121   122   123   124   125   126   127   128   129