You are on page 1of 38

Técnicas de Gestão de Base de Dados


Arrays

Funções

OOP

Marco António 1
Arrays

Fruta para 'pizza'


 Armazenamento de valores em variáveis:

<?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

$variavel = new array(valor, valor, ...);

 nome deve começar com uma letra ou


com _ (underscore)
 chave pré-definida: 0, 1, 2, etc.

$pizzaToppings[0]
$pizzaToppings[1]
$pizzaToppings[2]
...

Marco António 5
Arrays

Inserir e remover elementos num array


 array_push() - adiciona um elemento no final do array

<?php

// define an array
$pasta = array('spaghetti', 'penne', 'macaroni');

// add an element to the end


array_push($pasta, 'tagliatelle');

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');

// remove an element from the end


array_pop($pasta);

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');

// take an element off the top


array_shift($pasta);

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');

// add an element to the beginning


array_unshift($pasta, 'tagliatelle');

print_r($pasta);

?>

NOTA: array_push() e array_unshift() não funcionam com


arrays associativos.

Marco António 9
Arrays

Outras funções para trabalhar com arrays


 explode() - divide uma string, baseado em critério definido
pelo utilizador, devolvendo so componentes em elementos
de um array.

<?php

// define CSV string


$str = 'red, blue, green, yellow';

// split into individual words


$colors = explode(', ', $str);

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');

// join into single string with 'and'


// returns 'red and blue and green and yellow'
$str = implode(' and ', $colors);

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');

// returns the array sorted alphabetically


sort($pasta);
print_r($pasta);
print "<br />";

// returns the array sorted alphabetically in reverse


rsort($pasta);
print_r($pasta);
?>

Marco António 12
Arrays
 Leitura de valores de um array - exemplo1

<html><head></head><body> sizeof() - devolve o


My favourite bands are: nº de elementos do
<ul> array
<?php
// define array
$artists = array('Metallica', 'Evanescence', 'Linkin
Park', 'Guns n Roses');
// loop over it and print array elements
for ($x = 0; $x < sizeof($artists); $x++) {
echo '<li>'.$artists[$x];
}
?>

</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 />";

/* returns the array ('bacon and eggs', 'roast beef',


'lasagna') with numeric indices */
$result = array_values($menu);
print_r($result);
?>

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

foreach (expressao_array as $valor)


instrucoes
ou

foreach (expressao_array as $chave => $valor)


instrucoes

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

function function_name (optional function arguments) {


statement 1...
statement 2...
.
.
.
statement n...
}

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

Devolver o resultado da função

<?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);

/* call the same function with another argument and print


the return value */
print getCircumference(20);
?>

Marco António 21
Funções

Valores por defeito de parâmetros


<?php

// define a function
function introduce($name="John Doe", $place="London")
{
print "Hello, I am $name from $place";
}

// call function
introduce("Moonface");

?>

Output: Hello, I am Moonface from London

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

Variáveis – passagem por valor vs. passagem por referência


<?php
// create a variable
$today = "Saturday";
// function to print the value of the variable
function setDay($day) {
$day = "Tuesday"; <?php
print "It is $day inside the function<br />"; // create a variable
} $today = "Saturday";
// call function // function to print the value of the variable
setDay($today); function setDay(&$day) {
// print the value of the variable $day = "Tuesday";
print "It is $today outside the function"; print "It is $day inside the function<br />";
?> }
// call function
setDay($today);
// print the value of the variable
print "It is $today outside the function";
?>
Marco António 28
Funções

Vantagens da utilização de funções:

 funções construídas pelo programador permitem separar o


código em sub-secções bem identificadas;
 permitem criar um programa modular, permitindo a re-
utilização de código;
 simplificam alterações ao código, dado que as alterações
apenas são efectuadas uma vez.

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

public function eat() {


echo $this->name." is eating... "; }

public function run() {


echo $this->name." is running... "; }

public function kill() {


echo $this->name." is killing prey... "; }

public function sleep() {


echo $this->name." is sleeping... "; }
}
?>
Marco António 33
<?php
// my first bear
$daddy = new Bear;
// give him a name
$daddy->name = "Daddy Bear";
// how old is he
$daddy->age = 8;
// what sex is he
$daddy->sex = "male";

// and a baby
$baby = new Bear;
$baby->name = "Baby Bear";
$baby->age = 1;
$baby->sex = "male";

// a nice evening in the Bear family


// daddy kills prey and brings it home
$daddy->kill();

// baby eats
$baby->eat();
?>

Marco António 34
OOP

Criação de classes
<?php

// class definition
class Bear {

// define public properties


public $name;
public $age;

// define public methods


public function eat() {
echo $this->name." is eating... ";
// more code
}
// more methods
}
?>

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

You might also like