Functions (PHP)
Naar navigatie springen
Naar zoeken springen
The printable version is no longer supported and may have rendering errors. Please update your browser bookmarks and please use the default browser print function instead.
Simpel voorbeeld
Voorbeeld van een functie zonder retour-waardes (hoe noem je dat?):
<?php function double_the_number($a) { echo(2*$a); } double_the_number(4); ?>
Merk op:
- Ook numerieke variabelen zijn strings
- Zonder de aanroep (
double_the_number(4);
) wordt de functie niet uitgevoerd - De aanroep gaat zonder een keyword zoals
call
.
Return
Simpel voorbeeld:
<?php function square($num) { return $num * $num; } echo square(4); // outputs '16'. ?>
Een functie kan niet meerdere waardes uitvoeren - Een array is daarvoor de gebruikelijke oplossing
Je kunt het datatype van de uitvoer specificeren:
<?php function sum($a, $b): float { return $a + $b; } // Note that a float will be returned. var_dump(sum(1, 2)); ?>
Je kunt ook een object retourneren:
<?php # # Can I return a PDO-object from a funciton? ################################################################### # ############################################################### # Call wp-load.php ############################################################### # require_once("/home/strompf/www/rt.dvb/wp-load.php"); function create_pdo_object() { ############################################################### # Connect with dwh through PDO ############################################################### # $servername = "localhost"; $dbname = "example"; $username = "supervrouw"; $password = "invalid"; try { # Instantiate a new PDO object ############################## # $conn = new PDO("mysql:host=$servername;dbname=$dbname;charset=utf8", $username, $password); # set the PDO error mode to exception ##################################### # $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); echo "Connected successfully\n"; } catch(PDOException $e) { echo "Connection failed: " . $e->getMessage()."\n"; } return $conn; # TJAKKA! } $conn = create_pdo_object(); # WORKS! ############################################################### # Fetch & process table "product_tmp" ############################################################### # # Formulate query ################################################### # $sql = $conn->prepare("select * from product_tmp"); # Execute query ############### # $sql->execute(); # Fetch rows ############ # $rows = $sql->fetchAll(); print_r($rows); foreach ($rows as $row) { echo $row['sku']."\n"; }
Scope
- Variabelen zijn locaal
- Objecten zijn ook locaal!
Vraagstukken
- Hoe kun je binnen een functie een object instantiëren, die je daarbuiten ook kunt gebruiken? Iets met pass by reference?