Professional Documents
Culture Documents
●
Arrays
●
Funções
●
OOP
Marco António 1
Arrays
<?php
$i = 5;
?>
Marco António 2
Arrays
Outra forma de Aceder a valores guardados
armazenamento de valores num array:
em variáveis - arrays
$pizzaToppings[0]
$pizzaToppings[1]
<?php $pizzaToppings[2]
...
// define an array
$pizzaToppings = array('onion',
'tomato', 'cheese', 'anchovies', for ($i=0;$i<count($pizzaToppings)) {
'ham', 'pepperoni'); print_r($pizzaToppings[$i]);
}
print_r($pizzaToppings);
?>
Marco António 3
Arrays
Outra forma de representar Aceder a valores guardados
arrays: no array:
$fruits['red']
<?php $fruits['yellow']
$fruits['green']
// define an array ...
$fruits = array('red' => 'apple',
'yellow' => 'banana', 'purple' =>
'plum', 'green' => 'grape');
print_r($fruits);
?>
Marco António 4
Arrays
Regras e anotações na definição de arrays:
sintaxe
$pizzaToppings[0]
$pizzaToppings[1]
$pizzaToppings[2]
...
Marco António 5
Arrays
<?php
// define an array
$pasta = array('spaghetti', 'penne', 'macaroni');
print_r($pasta);
?>
Marco António 6
Arrays
array_pop() - remover um elemento do final do array
<?php
// define an array
$pasta = array('spaghetti', 'penne', 'macaroni');
print_r($pasta);
?>
Marco António 7
Arrays
array_shift() - remove um elemento do início do array
<?php
// define an array
$pasta = array('spaghetti', 'penne', 'macaroni');
print_r($pasta);
?>
Marco António 8
Arrays
array_unshift() - adicionar elementos no início do array
<?php
// define an array
$pasta = array('spaghetti', 'penne', 'macaroni');
print_r($pasta);
?>
Marco António 9
Arrays
<?php
print_r($colors);
?>
Marco António 10
Arrays
implode() - cria uma única string a partir dos elementos de
um array. Função inversa de explode().
<?php
// define array
$colors = array ('red', 'blue', 'green', 'yellow');
print $str;
?>
Marco António 11
Arrays
sort() - ordena ascendentemente, de forma alfabética ou
numérica, um array.
unsrot() - ordena descendentemente, de forma alfabética
ou numérica, um array.
<?php
// define an array
$pasta = array('spaghetti', 'penne', 'macaroni');
Marco António 12
Arrays
Leitura de valores de um array - exemplo1
</ul></body></html>
Marco António 13
Arrays
Leitura de valores de um array - exemplo2
<?php
// define an array array_keys() - lista
$menu = array('breakfast' => 'bacon and eggs', todas as chaves do
'lunch' => 'roast beef', 'dinner' => 'lasagna'); array
/* returns the array ('breakfast', 'lunch', 'dinner') with array_values() -
numeric indices */
$result = array_keys($menu);
lista todos os
print_r($result); valores do array
print "<br />";
Marco António 14
Arrays
Leitura de valores de um array - exemplo3
<html><head></head><body>
My favourite bands are: foreach() - forma
<ul> simplificada de
iterar arrays
<?php
// define array
$artists = array('Metallica', 'Evanescence', 'Linkin
Park', 'Guns n Roses');
// loop over it
// print array elements
foreach ($artists as $a) {
echo '<li>'.$a;
}
?>
</ul></body></html>
Marco António 15
Arrays
foreach()
sintaxe
Marco António 16
Funções
“ as your PHP scripts become more and more complex, it's only
a matter of time before you bump your head against the
constraints of the procedural method, and begin looking for a
more efficient way of structuring your PHP programs.
Solução?? - FUNÇÕES
”
Marco António 17
Funções
Funcionamento de uma função
<?php
// define a function
function myStandardResponse() {
echo "Get lost, jerk!<br /><br />";
}
// on the bus
echo "Hey lady, can you spare a dime? <br />";
myStandardResponse();
// at the office
echo "Can you handle Joe's workload, in addition to your own, while he's
in Tahiti for a month? You'll probably need to come in early and work till
midnight, but we are confident you can handle it. Oh, and we can't pay
you extra because of budgetary constraints...<br />";
myStandardResponse();
// at the party
echo "Hi, haven't I seen you somewhere before?<br />";
myStandardResponse();
?>
Marco António 18
Funções
Sintaxe básica
Marco António 19
Funções
Definição de argumentos
<?php
// define a function
function changeCase($str, $flag) {
/* check the flag variable and branch the code */
switch($flag) {
case 'U':
print strtoupper($str)."<br />";
break;
case 'L':
print strtolower($str)."<br />";
break;
default:
print $str."<br />";
break;
}
}
// call the function
changeCase("The cow jumped over the moon", "U");
changeCase("Hello Sam", "L");
?>
Marco António 20
Funções
<?php
// define a function
function getCircumference($radius) {
// return value
return (2 * $radius * pi());
}
/* call a function with an argument and store the result in a
variable */
$result = getCircumference(10);
Marco António 21
Funções
// define a function
function introduce($name="John Doe", $place="London")
{
print "Hello, I am $name from $place";
}
// call function
introduce("Moonface");
?>
Marco António 22
Funções
Passagem de um nº variável de argumentos
<?php
func_get_args() -
// define a function devolve um array que
function someFunc() { contém uma lista de
// get the arguments argumentos do array
$args = func_get_args();
func_num_args() -
// print the arguments devolve o nº de
print "You sent me the following arguments:"; argumentos
foreach ($args as $arg) { passados para a
print " $arg "; função
}
print "<br />";
}
// call a function with different arguments
someFunc("red", "green", "blue");
someFunc(1, "soap");
?>
Marco António 23
Funções
Variáveis e funções
<?php
// define a variable in the main program
$today = "Tuesday";
// define a function
function getDay() {
// define a variable inside the function
$today = "Saturday";
// print the variable
print "It is $today inside the function<br />";
}
Output:
// call the function It is Saturday
getDay(); inside the function
// print the variable It is Tuesday
print "It is $today outside the function"; outside the
?>
function
Marco António 24
Funções
Variáveis e funções
variáveis dentro da função não são “vistas” fora da função
variáveis fora da função não são “vistas” dentro da função
Este tipo de variável é designada por variável local.
Marco António 25
Funções
Variáveis globais
<?php
// define a variable in the main program
$today = "Tuesday";
// define a function
function getDay() {
// make the variable global
global $today; Output:
// define a variable inside the function It is Tuesday
$today = "Saturday";
// print the variable before running
print "It is $today inside the function<br />"; the function
} It is Saturday
// print the variable
print "It is $today before running the function<br />"; inside the
// call the function function
getDay(); It is Saturday
// print the variable
print "It is $today after running the function"; after running
?> the function
Marco António 26
Funções
Tipos de variáveis:
local
global
superglobal
Marco António 27
Funções
Marco António 29
OOP – Object Oriented Programming
Marco António 30
OOP
Classe, contém:
variáveis;
funções
Objecto, contém:
propriedades;
métodos
Marco António 31
OOP
Paródia animal
Consideremos um animal – o urso – que possui certas
características:
idade,
peso,
sexo, etc.
O urso realizada determinadas actividades como, por exemplo:
comer,
dormir,
andar,
correr,
acasalar, etc.
Marco António 32
<?php
// class definition
class Bear {
// define properties
public $name;
public $weight;
public $age;
public $sex;
public $colour;
// define methods
// and a baby
$baby = new Bear;
$baby->name = "Baby Bear";
$baby->age = 1;
$baby->sex = "male";
// baby eats
$baby->eat();
?>
Marco António 34
OOP
Criação de classes
<?php
// class definition
class Bear {
Marco António 35
OOP
Criação de objectos: Execução de métodos:
<?php
<?php
$daddy = new Bear;
$daddy->sleep();
?>
Definição de propriedades ?>
do objecto:
<?php
$daddy->name =
"Daddy Bear";
?>
Marco António 36
OOP
Construtor – função executada automaticamente para criar
um objecto quando é criada uma classe
<?php <?php
// class definition
class Bear { // create instance
// define properties $baby = new Bear;
public $name; $baby->name = "Baby Bear";
public $weight; echo $baby->name." is ".$baby-
public $age; >colour." and weighs ".$baby-
public $colour; >weight." units at birth";
// constructor ?>
public function __construct() {
$this->age = 0;
$this->weight = 100; Output: Baby Bear is brown
$this->colour = "brown"; and weighs 100 units at birth
}
}
?>
Marco António 37
<?php public function kill() {
echo $this->name." is killing prey... ";
// class definition }
class Bear {
// define properties public function sleep() {
public $name; echo $this->name." is sleeping... ";
public $weight; }
public $age; }
public $sex;
public $colour; // extended class definition
class PolarBear extends Bear {
// constructor
public function __construct() { // constructor
$this->age = 0; public function __construct() {
$this->weight = 100; parent::__construct();
} $this->colour = "white";
$this->weight = 600;
// define methods }
public function eat($units) {
echo $this->name." is eating ".$units." units // define methods
of food... "; public function swim() {
$this->weight += $units; echo $this->name." is swimming... ";
} }
}
public function run() {
echo $this->name." is running... "; ?>
}
Marco António 38