PHP Functions
Jussi Pohjolainen
Intro to php functions
- PHP has lots of predefined functions. [See list]
- For example:
$date_str = date("m.d.y");
- It is possible to create your own functions.
- Each function should perform a single simple task
Function example
say_hello();
Parameters
say_hello("Jack Bauer");
More Parameters
say_hello("Jack Bauer", 12);
Default parameters
say_hello("Jack Bauer");
say_hello("Jack Bauer", 12);
Function return values
$text = hello("Jack Bauer", 12);
Namespacing
- Namespacing is critical in large code base.
- PHP does not have real namespaces.. use classes instead.
- Classes can have static and non-static methods. If class
holds only static methods, you can think that the class is
like a namespace
Dividing code
- Try to separate GUI (html) and BL (Business logic) from each
other
- Simple way is to use functions. Put as much as logic you
can in to functions and call them from GUI. This way the code is much easier
to read and maintain.
- See bad- vs.
good-examples.
Intro to OO (Object-orientated) programming
- The biggest change in PHP 5 is the support for OO-techniques
- Traditional way of programming in PHP is to use procedural programming
concepts
- When the software project gets large, it's recommerend to use OO-techniques
- OO-programming holds many concepts: class, object, inheritance, encapsulation, methods, polymorphism
- See OO-example