PHP5 Básico
description
Transcript of PHP5 Básico
![Page 1: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/1.jpg)
PHP5 BÁSICO40 Horas
Instrutor: Antonio Itamar Júnior
![Page 2: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/2.jpg)
PHP5 BÁSICO
• O que é PHP?• Nomenclatura de arquivos• Abertura de escopo PHP• Comentários de código• Variáveis• Nomenclatura de variáveis• Tipos de dados
- Array
- Programação Web
- Orientação a Objetos
- MySQL
- PHP + MySQL
![Page 3: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/3.jpg)
AMBIENTE DE DESENVOLVIMENTO
Links para apache e php5
3
![Page 4: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/4.jpg)
O QUE É PHP?
4
![Page 5: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/5.jpg)
NOMENCLATURA DE ARQUIVOS
Não pode conter caracteres especiais. Nomes válidos:
Arquivo2.php nomeArquivo.php nome_arquivo.php Cliente.php
Nomes inválidos: nome arquivo.php nome-arquivo.php Formulário.php
5
![Page 6: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/6.jpg)
ESTUDO DE CASO
Crie os arquivos para as seguintes necessidades. Cadastrar Pessoa Jurídica; Cadastrar Nome Completo da Mãe; Formulário de inscrição
6
![Page 7: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/7.jpg)
ABERTURA DE ESCOPO PHP
Sintaxe
Sintaxe alternativa (exige alteração no PHP.INI)
7
<?php ...?>
<? ?>
![Page 8: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/8.jpg)
COMENTÁRIOS DE CÓDIGO
Mantém textos dentro do escopo de um código PHP, sem ser interpretado pelo servidor;
Auxilia a equipe a entender um determinado trecho de código;
Sintaxe Pequenos comentários – recomendado para frase unica;
Grandes comentários – recomentado para explicar um algorítimo;
Grandes comentários – recomendado para explicar funcionalidades pelo fato de auxilizar na geração de documentação do código.
8
// Texto em linha única
/* * Texto em * várias linhas */
/** * Texto em * várias linhas */
![Page 9: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/9.jpg)
VARIÁVEIS
Similar a aritmética , as variáveis servem para armazenar algum valor desconhecido, ou que muda com certa facilidade.
Para criar uma variável é necessário colocar o símbolo “$” antes do nome desejado.
Sintaxe
9
$nome_da_varivel
![Page 10: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/10.jpg)
NOMENCLATURA DE VARIÁVEIS Não pode ser iniciada com número; É case-sensitive, $nome é diferente de $NOME;
10
Válidos Inválidos
$Nome $2nome;
$nome $nome completo;
$_nome -
$nomeCompleto *
$nome_completo /
![Page 11: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/11.jpg)
ALIMENTAR VARIÁVEIS
Valor numérico;
Valor alfanumérico
Valor variável
11
$variavel = valor;
Da esquerda pra direita
$variavel = 10;
$variavel = “Hello World”;
$variavel = 10.5;
$variavel = “10”;
$variavel = “10.5”;
$variavel = $variavel_2;
![Page 12: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/12.jpg)
TIPOS DE DADOS
O tipo de variável se refere ao tipo de dado que é armazenado em uma variável.
12
Tipo Descrição
Int Utilizado para números inteiros
Float Também chamado de Double – Utilizado para números reais (números de ponto flutuante)
String Utilizado para coleções de caracteres (textos)
Boolean Utilizado para valores verdadeiros ou falsos.
Array Utilizado para armazenar vários valores
Object
Resource
NULL Atribuído automaticamente quando não é declarado nenhum tipo para uma variável
![Page 13: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/13.jpg)
TIPOS DE DADOS
No PHP não há necessidade de declarar o tipo da variável antes de utilizá-la, como é obrigatório em linguagens como C e JAVA.
13
![Page 14: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/14.jpg)
APRENDA FAZENDO
A variável quantidade agora é entendida como uma variável do tipo Int e a variável preco como Float.
Provando a portabilidade de tipos de variável no PHP, agora à variável preco será entendida como sendo do tipo String.
O PHP altera o tipo de variável de acordo com o que está armazenado na variável. Em qualquer momento essa troca pode ocorrer.
14
<?php $quantidade = 0; $preco = 0.00;?>
<?php $quantidade = 0; $preco = ‘Brasil’;?>
![Page 15: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/15.jpg)
COERÇÃO DE TIPO
Para fazer uma coerção basta colocar o tipo desejado entre parênteses “()” na frente da variável.
Para fazer uma coerção basta colocar o tipo desejado entre parênteses “()” na frente da variável.
15
$variavel = (tipo) $variavel;
Possíveis Tipos
int integer
float long
double real
![Page 16: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/16.jpg)
APRENDA FAZENDO
Aplicando coerção de tipo
A variável $preco, está armazenando a coerção da variável $quantidade para o tipo real.
A variável $quantidade continua sendo do tipo int. A variável $preco fica sendo do tipo float.
16
<?php $quantidade = 10; $preco = (double) $quantidade;?>
![Page 17: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/17.jpg)
VISUALIZANDO VARIÁVEIS NO BROWSER
Echo var_dump();
Aprenda fazendo para visualizar as variaveis.
17
![Page 18: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/18.jpg)
VARIÁVEIS VARIÁVEL
Através das variáveis variável é permitido alterar dinamicamente o nome de uma variável.
18
<?php $nome = ‘hoje’; $$nome = 5;
echo $hoje;
echo ‘<br />’;
//A variável terá o nome inválido, portanto não irá funcionar
$nome = '123'; $$nome = '456'; echo $123;
?>
![Page 19: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/19.jpg)
CONSTANTES Uma constante armazena um valor como uma variável, mas seu
valor é atribuído uma vez e não pode ser alterado em outra parte do script.
Nomenclatura similar as variáveis normais, com algumas pequenas diferenças:
Usar nome em maiúsculo, para distinguir variáveis de constantes. (Não é obrigado, mas facilita a leitura do código)
Obrigatoriamente não colocar o sinal de cifrão “$” na frente do nome. Case sensitive
19
<?php define( "MONITOR" , 700 ); define( "LOCAL" , "Brasil" ); define( "VALIDO" , true ); define( "1CARRO" , 3 ); //Nome inválido
echo MONITOR; echo “<br />"; echo LOCAL; echo “<br />"; echo VALIDO;?>
![Page 20: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/20.jpg)
CONSTANTES MÁGICAS
http://www.php.net/manual/pt_BR/language.constants.predefined.php
20
![Page 21: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/21.jpg)
OPERADORES
Desenvolvimento...
21
![Page 22: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/22.jpg)
OPERADORES ARITMÉTICOS
Similares aos operadores matemáticos.
22
Nome Operador Exemplo
Adição + $a + $b
Subtração - $a - $b
Multiplicação * $a * $b
Divisão / $a / $b
Módulo % $a % $b
![Page 23: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/23.jpg)
OPERADORES ARITMÉTICOS
Similares aos operadores matemáticos.
23
Nome Operador Exemplo
Adição + $a + $b
Subtração - $a - $b
Multiplicação * $a * $b
Divisão / $a / $b
Módulo % $a % $b
![Page 24: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/24.jpg)
APRENDA FAZENDO
Escreva o código abaixo no arquivo operadores_aritmeticos.php
24
<?php
//ALIMENTANDO VARIÁVEIS $a = 1; $b = 2; $c = 3; $d = 4; $e = -1;
//OPERADOR DE ADIÇÃO $adicao = $a + $b; //OPERADOR DE SUBTRAÇÃO $subtracao = $c - $a; //OPERADOR DE MULTIPLICAÇÃO $multiplicacao = $b * $c; //OPERADOR DE DIVISÃO $divisao = $d / $b;
//OPERADOR DE MÓDULO $modulo = $d % $c; ?>
![Page 25: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/25.jpg)
ESTUDO DE CASO
Imprima o nome da operação e a operação com resultado.
…Continue com as outras operações.
25
<?php
//IMPRIMIR RESULTADOS
echo "Adicao : "; echo $a; echo " + "; echo $b; echo " = "; echo $adicao;
echo "<br />";
echo "Subtracao : "; echo $c; echo " - "; echo $a; echo " = "; echo $subtracao;
echo "<br />"; ?>
![Page 26: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/26.jpg)
OPERADOR DE STRING
Conhecido como concatenação, é possível juntar e armazenas uma ou mais strings.
26
<?php
$nome = "Antonio Itamar"; $sobrenome = " Junior";
$nome_completo = $nome . $sobrenome;
echo $nome_completo;
?>
![Page 27: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/27.jpg)
APRENDA FAZENDO
Escreva o código abaixo no arquivo operador_string.php
27
<?php
$nome = "Antonio Itamar"; $sobrenome = " Junior";
$nome_completo = $nome . $sobrenome;
echo $nome_completo; ?>
![Page 28: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/28.jpg)
CONCATENAÇÃO AVANÇADA
28
![Page 29: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/29.jpg)
OPERADORES DE ATRIBUIÇÃO DE COMBINAÇÃO
Cada um dos operadores abaixo, é um modo abreviado de fazer uma operação aritmética.
29
Operador Utilização Equivalente a
+= $a += $b $a = $a + $b
-= $a -= $b $a = $a - $b
*= $a *= $b $a = $a * $b
/= $a /= $b $a = $a / $b
%= $a %= $b $a = $a % $b
.= $a .= $b $a = $a . $b
![Page 30: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/30.jpg)
APRENDA FAZENDO
30
<?php
$a = $a . “Oi"; echo $a . $a = $a . “Brasil"; $a = $a . "Teste";
$a = $a . "Teste"; $sobrenome = " Junior";
$nome_completo = $nome . $sobrenome;
echo $nome_completo;
?>
![Page 31: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/31.jpg)
AULA 2
• Pré e pós incremento e decremento
![Page 32: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/32.jpg)
PRÉ E PÓS INCREMENTO E DECREMENTO
32
Pré-incremento – primeiro incrementa (+1) na variável informada em seguida retorna o valor incrementado.
Pós-incremento – primeiro retorna o valor da variável em seguida é incrementado (+1).
Para decrementar (--) é semelhante, entretanto o valor da variável vai decrementar em vez de incrementar.
++$variavel;
$variavel++;
![Page 33: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/33.jpg)
APRENDA FAZENDO
Escreva o código abaixo no arquivo pre_pos_incremento.php
33
<?php
echo 'Pos-Incremento'; echo '<br />'; echo 'Primeira Chamada = ' . $i++; echo '<br />'; echo 'Segunda Chamada = ' . $i; echo '<br />'; echo '<br />';
echo 'Pre-Incremento'; echo '<br />'; echo 'Primeira Chamada = ' . ++$j; echo '<br />'; echo 'Segunda Chamada = ' . $j;
?>
![Page 34: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/34.jpg)
diferença de = para ==
34
![Page 35: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/35.jpg)
ESTRUTURA DE CONTROLE: INSTRUÇÃO IF
Case sensitive; Sintaxe para única instrução
Sintaxe para várias instruções
Sintaxe alternativa Substitui a chave de abertura ({) por dois-pontos (:) e a chave de
fechamento por uma nova palavra-chave, que será endif
35
if( expressão Boolean ) instruções
if( expressão Boolean ){ instruções}
if( expressão Boolean ): instruçõesendif;
![Page 36: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/36.jpg)
APRENDA FAZENDO
36
![Page 37: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/37.jpg)
TABELA DA VERDADE
E | OU
If com mais de uma condição.
37
![Page 38: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/38.jpg)
ESTRUTURA DE CONTROLE: INSTRUÇÃO ELSE
38
![Page 39: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/39.jpg)
ESTRUTURA DE CONTROLE: INSTRUÇÃO ELSEIF
39
![Page 40: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/40.jpg)
ESTUDO DE CASO
40
![Page 41: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/41.jpg)
ESTRUTURA DE CONTROLE: INSTRUÇÃO SWITCH
Funciona de modo semelhante a instrução if. Sintaxe
A palavra-chave break quer dizer que a instrução irá parar assim que encontrá-la. 41
switch ( $a ){ case 'Brasil': //EXECUTA AÇÃO break;
case 5: //EXECUTA AÇÃO break;
default: //EXECUTA AÇÃO break;}
![Page 42: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/42.jpg)
APRENDA FAZENDO
Escreva o código abaixo no arquivo switch.php
42
<?php
$a = ‘Brasil’; switch ( $a ) { case 'Brasil': echo ‘Sou Brasileiro’; break;
case 'Argentina‘: echo "Sou Argentino"; break;
case 'Estados Unidos': echo 'Sou Norte Americano'; break;
default: echo 'Não possuo nacionalidade'; break; } ?>
![Page 43: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/43.jpg)
ESTRUTURA DE CONTROLE PARA REPETIÇÃO
As instruções while, do-while, for e foreach, são consideradas instruções de controle iterativo (repetição), podendo executar alguma parte do código várias vezes.
43
![Page 44: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/44.jpg)
ESTRUTURA DE CONTROLE: INSTRUÇÃO WHILE
Como em uma instrução if ele conta com uma condição seja ‘true’ ou ‘false’.
No início de cada iteração, a condição será testada, se a condição for true a instrução será executada, caso seja false, o bloco não será executado e o loop terminará.
Sintaxe
Sintaxe alternativa
44
while( expressão Boolean ){ instruções}
while( expressão Boolean ): instruçõesendwhile;
![Page 45: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/45.jpg)
APRENDA FAZENDO
Escreva o código abaixo no arquivo while.php
45
<?php
$a = 0; while ( $a < 10 ) { echo $a . ‘<br />'; $a++; } ?>
![Page 46: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/46.jpg)
ESTRUTURA DE CONTROLE: INSTRUÇÃO DO-WHILE
Loops do-while são bem similares aos loops while, exceto pelo fato de que a condição é verificada no fim de cada iteração em vez de no começo.
A primeira iteração de um loop do-while é garantidamente executada (a condição só é verificada no fim da iteração) .
Não é obrigatório executar o loop (condição diferente de true).
Sintaxe única
46
do{ instruções}while( expressão Boolean );
![Page 47: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/47.jpg)
APRENDA FAZENDO
Escreva o código abaixo no arquivo do_while.php
47
<?php
//EXECUTA A PRIMEIRA ITERAÇÃO, E ENTRA NO LOOP $a = 0; do { echo $a . ‘<br />'; $a++; } while ( $a < 10 );
echo ‘<br />';
//EXECUTA APENAS A PRIMEIRA ITERAÇÃO, MAS NÃO EXECUTA O LOOP $a = 0; do { echo $a . ‘<br />'; $a++; } while ( $a > 10 );
?>
![Page 48: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/48.jpg)
ESTRUTURA DE CONTROLE: INSTRUÇÃO FOR Sintaxe
Expressão 1 – é executada uma vez incondicionalmente no início do loop (normalmente valor inicial de um contador).
Expressão 2 – é avaliada no início de cada iteração, se a expressão for true o loop continua, caso seja false o loop termina (normalmente testará o contador com um limite).
Expressão 3 – é executada no fim de cada iteração (normalmente ajustará o valor do contador).
Sintaxe alternativa 48
for( expressão 1 ; expressão 2 ; expressão 3 ){ instruções}
for( expressão 1 ; expressão 2 ; expressão 3 ): instruçõesendfor;
![Page 49: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/49.jpg)
APRENDA FAZENDO
Escreva o código abaixo no arquivo for.php
49
<?php
//SINTAXE 1 for ( $a = 1; $a <= 10; $a++ ) { echo $a . ‘ ‘; }
?>
![Page 50: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/50.jpg)
ESTRUTURA DE CONTROLE: INSTRUÇÃO FOR
Cada uma das expressões pode ser vazia ou conter múltiplas expressões separadas por vírgulas.
Em expr2, todas as expressões separadas por vírgula são avaliadas mas o resultado é obtido pela última parte.
expr2 vazia significa que o loop pode rodar indefinidamente (PHP considera-a implicitamente como TRUE, como em C).
50
![Page 51: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/51.jpg)
APRENDA FAZENDO
Escreva o código abaixo no arquivo for.php
51
<?php
//SINTAXE 1 for ( $a = 1; $a <= 10; $a++ ) { echo $a . ‘ ‘; }
echo ‘<br />‘;
//SINTAXE 2 for ( $a = 1; ; $a++ ) { if ( $a > 10 ) { break; } echo $a . ‘ ‘; }
?>
![Page 52: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/52.jpg)
ESTRUTURA DE CONTROLE: BREAK E CONTINUE
break cancela a execução do comando for, foreach, while, do-while ou switch atual.
break aceita um argumento numérico opcional que diz a ele quantas estruturas aninhadas englobadas devem ser quebradas.
http://www.php.net/manual/pt_BR/control-structures.break.php
52
![Page 53: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/53.jpg)
ESTRUTURA DE CONTROLE: INSTRUÇÃO DECLARE
O construtor declare é utilizado para configurar diretivas de execução para blocos de código. A sintaxe do declare é similar a sintaxe de outros construtores de controle.
http://br2.php.net/manual/pt_BR/control-structures.declare.php
53
![Page 54: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/54.jpg)
AULA 3
• Array
![Page 55: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/55.jpg)
FUNÇÕES DO PHP
Conheça algumas forma de visualizar o conteúdo de um array.
55
Função Descrição
var_damp() Utilizado para representação estruturada sobre uma ou mais expressões, incluindo o tipo, a chave e o valor
print_r() Utilizado para imprimir a estrutura de um array, contendo a chave e o valor
<pre></pre> Tag HTML para formatar uma saída (texto).
![Page 56: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/56.jpg)
APRENDA FAZENDO
Escreva o código abaixo no arquivo array.php
56
<?php $a = array( 10 , 20 , 30 );
//IMPRIMINDO ARRAY - VAR_DUMP var_dump( $a );
echo '<br />‘;
//IMPRIMINDO ARRAY - PRINT_R print_r( $a );
echo '<br />';
//FORMATANDO IMPRESSÃO - VAR_DUMP echo '<pre>'; var_dump( $a ); echo '</pre>'; echo '<br />';
//FORMATANDO IMPRESSÃO - PRINT_R echo '<pre>'; print_r( $a ); echo '</pre>';
?>
![Page 57: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/57.jpg)
ARRAY – ACESSANDO CONTEÚDO
Arquivo: acessando_array.php
Observação: Echo $a[] // vai dar erro.
57
<?php $a = array( 10 , 20 , 30 , ‘Brasil’ , true , 30.7 );
echo $a[0] . '<br />‘; echo $a[1] . '<br />‘; echo $a[2] . '<br />‘; echo $a[3] . '<br />‘; echo $a[4] . '<br />‘; echo $a[5] . '<br />‘;
Manipular valor echo $a[0] = ‘Alterando valor da posição 0.‘; echo $a[0] . '<br />‘;
?>
![Page 58: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/58.jpg)
ESTUDO DE CASO – ACESSANDO ARRAY
Arquivo: estudo_caso_acessando_array.php
58
<?php $a = array( 10 , 20 , 30 , ‘Brasil’ , true , 30.7 );
For( $i = 0 ; $i <= 5 ; $i++ ) { echo $a[$i] . '<br />‘; }
?>
![Page 59: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/59.jpg)
ARRAYS COM ÍNDICES (CHAVES)
O função array por padrão já cria automaticamente suas chaves, iniciando com 0 e indo até N;
A chave pode ser string ou integer; Arrays com chaves Float, serão transformados em Int; Utilizar True como chave será interpretado como Integer 1. Utilizando False como chave será avaliado como Integer 0. Utilizando Null como chave será avaliada como uma String vazia. O valor pode ser qualquer tipo PHP;
Sintaxe
59
array( chave => valor , ... )
![Page 60: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/60.jpg)
ACESSANDO CONTEÚDO DE ARRAY COM CHAVES
Declara o array com todas as chaves e valores necessários
Declara o array com apena uma chave e um valor, implementando o resto depois da declaração inicial do array
Não foi iniciado nenhum array
60
$a = array( 'mouse' => 30 , 'monitor' => 400 , 'teclado' => 45 );
$a = array( 'mouse’ => 30 ); $a['monitor'] = 400; $a['teclado'] = 45;
$a[‘mouse'] = 30; $a['monitor'] = 400; $a['teclado'] = 45;
![Page 61: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/61.jpg)
APRENDA FAZENDO
Escreva o código abaixo no arquivo array_chave.php (1/2)
61
<?php //SINTAXE 1 $a = array( 'mouse' => 30 , 'monitor' => 400 , 'teclado' => 45 );
//SINTAXE 2 $b = array( 'mouse' => 30 ); $b['monitor'] = 400; $b['teclado'] = 45;
//SINTAXE 3 $c['mouse'] = 30; $c['monitor'] = 400; $c['teclado'] = 45;
//EXIBIR CONTEÚDO echo $a['mouse'] . '<br />'; echo $b['teclado'] . '<br />'; echo $c['monitor'] . '<br />';
![Page 62: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/62.jpg)
...CONTINUAÇÃO
Escreva o código abaixo no arquivo array_chave.php (2/2)
62
$d = array( 'a' => true , 3 => 20 , 5.3 => 30 , true => 'Texto 1' , false => 'Texto 2' , null => 'Texto3‘ ); //IMPRIMIR ARRAY - VAR_DUMP echo '<pre>'; var_dump( $d ); echo '</pre>'; echo '<br />';
//FORMATANDO IMPRESSÃO - PRINT_R echo '<pre>'; print_r( $d ); echo '</pre>';
?>
![Page 63: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/63.jpg)
FUNÇÕES DO PHP
Conheça algumas forma de visualizar o conteúdo de um array utilizando funções de iteração.
63
Função Descrição
foreach Estrutura de controle similar a while e for, oferecendo uma maneira fácil de iterar sobre arrays ( matrizes)
![Page 64: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/64.jpg)
ESTRUTURA DE CONTROLE: INSTRUÇÃO FOREACH
O foreach funciona somente com variáveis do tipo arrays, qualquer variável diferente de array a função retornará um erro “Warning: Invalid argument supplied for foreach()”
Sintaxe
Varre uma matriz dada por variavel_array. Em cada 'loop', o valor do elemento corrente é atribuído a $valor .
Sintaxe alternativa
Atribui a chave do elemento atual à variável $chave em cada iteração.
64
foreach ( variavel_array as $valor ){ instrucoes}
foreach ( variavel_array as $chave => $valor ){ instrucoes}
![Page 65: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/65.jpg)
APRENDA FAZENDO
Escreva o código abaixo no arquivo foreach.php
65
<?php $a = array( ‘mouse’ => 30 , 'monitor' => 400 , 'teclado' => 45 );
//SINTAXE 1 foreach ( $a as $valor ) { echo $valor . ' '; }
echo '<br />'; echo '<br />';
//SINTAXE 2 foreach ( $a as $chave => $valor ) { echo 'Chave: ' . $chave . ', valor: ' . $valor . '<br />'; }?>
![Page 66: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/66.jpg)
OPERADORES DE ARRAY
66
Nome Operador Exemplo Resultado
União + $a + $b O array $b é anexado a $a, mas os conflitos de chaves não são adicionados, prevalecendo $a
Igualdade == $a == $b Verdadeiro se $a e $b contêm os mesmos valores com as mesmas chaves.
Identidade === $a === $b Verdadeiro se $a e $b contêm os mesmos valores do mesmo tipo na mesma ordem com as mesmas chaves.
Desigualdade != $a != $b Verdadeiro se $a e $b não contêm os mesmos valores.
Desigualdade <> $a <> $b O mesmo que !=.
Não-identidade !== $a !== $b Verdadeiro se $a e $b não contêm os mesmos valores do mesmo tipo na mesma ordem.
![Page 67: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/67.jpg)
APRENDA FAZENDO
Escreva o código abaixo no arquivo array_operadores.php
67
<pre> <?php
$a = array( 1 , 2 , 3 ); $b = array( 'a' => 1 , 2 , 3 ); $c = array( 1 => 2 , 2 => 3 , 0 => 1 ); $d = array( '1' , '2' , '3' ); $e = array( 5 => 'Brasil' , 6 => 'Argentina' , 7 => 'Chile' ); //UNIÃO DE ARRAYS print_r( $a + $b );
//UNIÃO DE ARRAYS print_r( $a + $e );
//IGUALDADE DE ARRAYS var_dump( $a == $c );
//IDENTIDADE DE ARRAYS var_dump( $a === $c );
//IDENTIDADE DE ARRAYS var_dump( $a === $d ); ?></pre>
![Page 68: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/68.jpg)
AULA 4
• Função
![Page 69: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/69.jpg)
FUNÇÕES
São utilizadas para encapsular um pedaço de código que realiza uma tarefa única e bem definida.
Não é possível cancelar ou alterar a definição de funções previamente declaradas.
Qualquer código PHP válido pode aparecer dentro de uma função, mesmo outras funções.
É iniciada com a palavra-chave function. Sintaxe declaração
Sintaxe chamada69
function nome(){ instruções da função}
nome();
![Page 70: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/70.jpg)
FUNÇÕES – NOMENCLATURA
É importante considerar que o nome da função deve ser descritivo – descrever o que a função faz.
Não é possível sobrepor uma função – não é possível ter mais de uma função com o mesmo nome.
Não é permitido cria uma função com o mesmo nome de uma função predefinida pelo PHP.
Somente é permitido: letras , número e sublinhados. Não pode iniciar com número. Não é case-sensitive – nome() é igual a NOME().
70
Válido Inválido
nome() 5nome()
nome2() somar-numeros()
_nome_tres() $exibir()
nomeQuatro() count()
![Page 71: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/71.jpg)
APRENDA FAZENDO
Escreva o código abaixo no arquivo funcao.php
Chamando funções
71
<?php function hello() { echo 'Hello World'; }?>
<?php $nome = ‘hello’; function hello() { echo 'Hello World‘ . ‘<br />’; }
hello(); $nome(); ?>
nome_da_função();$nome_da_variável();
![Page 72: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/72.jpg)
FUNÇÕES – ESCOPO
Conclusão O que esta dentro da função só funciona dentro; O que esta fora só funciona fora da função;
Todas as funções no PHP tem escopo global - elas podem ser chamadas fora de uma função mesmo que tenham sido definidas dentro e vice-versa.
72
$a = 1; echo $a; //Exibe 1 function hello() { echo $a; //Não exibe nada } echo $a; //Exibe 1
$a = 1; echo $a; //Exibe 1 function hello() { $a = 3; $b = 5; echo $a; //Exibe 3 echo $b; //Exibe 5 } echo $a; //Exibe 1 echo $b; //Não exibe nada
![Page 73: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/73.jpg)
FUNÇÕES – RETORNO
Funciona como um exit na função. Diferença: echo X return
73
<?php function hello() { echo 'Hello World'; }
hello();?>
<?php function hello() { return ( 'Hello World' ); }
echo hello();?>
![Page 74: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/74.jpg)
APRENDA FAZENDO
Escreva o código abaixo no arquivo funcao_retorno.php
74
<?php function hello() { return ( 'Hello World' ); }
echo hello(); $a = hello();?>
![Page 75: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/75.jpg)
ESTUDO DE CASO – FUNÇÃO
75
![Page 76: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/76.jpg)
FUNÇÕES – PARÂMETRO
Os parâmetros permitem introduzir vários valores em uma função para influenciar seu comportamento.
Todos os parâmetros serão obrigatórios excerto quando for definido como opcional (atribuído um valor padrão).
É permitido informar mais parâmetros do que foi declarado na função.
Não é permitido informar menos parâmetros do que foi declarado.
Sintaxe
76
function nome( $par1 , $par2 , .... ){}
function nome( $par1 , $par2 , $par3 = 1 , .... ){}
![Page 77: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/77.jpg)
APRENDA FAZENDO
Escreva o código abaixo no arquivo funcao_parametro.php
77
<?php function hello( $par1 ) { echo 'Hello ' . $par1; }
hello( 'World' );
echo '<br />';
//FUNÇÃO COM VALOR OPCIONAL
function hello2( $par1 , $par2 = 'Blue' ) { echo 'Hello ' . $par1 . ' ' . $par2; }
hello2( 'World' );
echo '<br />';
hello2( 'World' , 'red' );
?>
![Page 78: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/78.jpg)
ESCOPO DE VARIÁVEIS
Escopo refere-se ao local onde a variável é visível.
78
Superglobal Visíveis por toda parte dentro de um script
Constantes Uma vez declarada, são sempre visíveis globalmente, podem ser usadas dentro e fora das funções
Variáveis Declaradas em um script são visíveis por todo esse script, mas não dentro de funções
![Page 79: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/79.jpg)
79
<?php function calculadora( $num1 , $num2 , $operacao ) { if ( $operacao == "adicao" ) { $resultado = $num1 + $num2; } elseif ( $operacao == "subtracao" ) { $resultado = $num1 - $num2; } elseif ( $operacao == "multiplicacao" ) { $resultado = $num1 * $num2; } elseif ( $operacao == "divisao" ) { $resultado = $num1 / $num2; } else { $resultado = "Informe uma operacao valida”; }
return ( $resultado ); }
echo calculadora( 1 , 2 , “adicao" );
?>
![Page 80: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/80.jpg)
80
<?php function imprimirArray( $par1 ) { foreach ( $par1 as $valor ) { $b = $b . $valor; } return ( $b ); }
$a = array( 1 , 2 , 3 , 4 , 5 );
echo imprimirArray( $a );
?>
![Page 81: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/81.jpg)
FUNÇÕES – PARÂMETRO POR REFERÊNCIA
Veja aprenda fazendo.
81
![Page 82: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/82.jpg)
APRENDA FAZENDO Escreva o código abaixo no arquivo funcao_parametro_por_referencia.php
82
<?php function incrementar( &$par1 , $incremento = 1 ) { $par1 = $par1 + $incremento; }
$valor = 10; echo $valor . '<br />'; incrementar( $valor ); echo $valor . '<br />';
echo '<br />';
$valor2 = 20; echo $valor2 . '<br />'; incrementar( $valor2 , 5 ); echo $valor2 . '<br />';
?>
![Page 83: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/83.jpg)
AULA 5
• Orientação a Objetos
![Page 84: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/84.jpg)
ORIENTAÇÃO A OBJETOS – 10 HORAS
- Declaração de classe
- Nomenclatura
- Instanciar classe
- Utilizar atributos e métodos de classe
![Page 85: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/85.jpg)
OOP – PROGRAMAÇÃO ORIENTADA A OBJETOS
85
![Page 86: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/86.jpg)
DECLARAÇÃO DE CLASSE
A classe é formada por: Atributos ( variáveis ) utilizando a palavra-chave var; Métodos ( funções ) utilizando a palavra-chave function;
Sintaxe
86
class NomeDaClasse{ var $atributo;
function metodo() { }}
![Page 87: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/87.jpg)
APRENDA FAZENDO
Escreva o código abaixo no arquivo classe.php
87
<?php class NomeDaClasse { var $atributo1; var $atributo2;
function metodo1() { }
function metodo2( $par1 , $par2 ) {
}
}
?>
![Page 88: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/88.jpg)
NOMENCLATURA
Não é possível declarar mais de um atributo ou método com o mesmo nome.
Classe Atributo Método
88
![Page 89: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/89.jpg)
INSTANCIAR CLASSE
Após declarar uma classe, é possível criar um ou vários objetos que seja membro dela.
A criação de objetos é conhecida também como criar uma instância ou instanciar uma classe.
Para informar ao servidor que queremos instanciar uma classe iremos utilizar a palavra-chave new.
Neste momento, a variável $a possui um objeto da classe NomeDaClasse. 89
class NomeDaClasse{ var $atributo;
function metodo() { }}
$a = new NomeDaClasse();
![Page 90: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/90.jpg)
UTILIZAR ATRIBUTOS E MÉTODOS DE CLASSE
Todos os atributos e métodos de uma classe pertencem apenas ao escopo da classe e de seus objetos,
Não é possível utilizar um atributo ou chamar um método sem referenciar sua classe.
Sintaxe para utilização fora da classe.
90
class NomeDaClasse{ var $atributo;
function metodo() { }}
$a = new NomeDaClasse();$a->atributo;$a->atributo = 1;$a->metodo();
![Page 91: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/91.jpg)
APRENDA FAZENDO
Escreva o código abaixo no arquivo instanciar_classe.php
91
<?php class Carro { var $ano; var $cor;
function andar() { return('Método que faz o carro andar!'); } }
//CRIAR UMA INSTÂNCIA DA CLASSE CARRO. $carro1 = new Carro();
//ATRIBUIR VALORES AO OBJETO. $carro1->ano = 2009; $carro1->cor = 'Prata';
//IMPRIMIR VALORES DO OBJETO. echo $carro1->ano; echo '<br />'; echo $carro1->cor; echo '<br />';
//CHAMAR FUNCIONALIDADES DO OBJETO. echo $carro1->andar(); ?>
![Page 92: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/92.jpg)
ESTUDO DE CASO – PROCURAR EXEMPLOS QUE EXEMPLIFIQUE A USO DE HERANÇA, POIS SERA UTIL PARA APROVEITAR NESSE ESTUDO DE CASO
Arquivo: estudo_caso_instanciar_classe.php
Impressão:
Ano: 2009
Cor: Preto
Velocidade: 300
Moto andando…
Moto Parada
92
Transporte
+ ano+ cor+ velocidade
+ andar()+ parar()
![Page 93: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/93.jpg)
UTILIZAR ATRIBUTO E MÉTODO INTERNO
Para ter acesso a atributos ou métodos dentro de uma classe, deverá ser utilizado a palavra-chave $this ( variável nativa ).
$this é uma usada para referenciar o objeto corrente (objeto utilizado no momento).
Sintaxe para utilização dentro da classe.
93
class NomeDaClasse{ var $atributo;
function metodo() { $this->atributo; $this->metodo2(); }
function metodo2() { }}
$a = new NomeDaClasse();$a->atributo = 3;$a->metodo();
![Page 94: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/94.jpg)
94
![Page 95: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/95.jpg)
95
<?php class Carro { var $ano; var $cor; function andar() { return( 'Método que faz o carro andar!<br />‘ . $this->obterInformacao() ); }
function obterInformacao() { return('Informações obtidas - Ano: ' . $this->ano . ' , Cor: ' . $this->cor); } }
//CRIAR UMA INSTÂNCIA DA CLASSE CARRO. $carro1 = new Carro();
//ATRIBUIR VALORES AO OBJETO. $carro1->ano = 2009; $carro1->cor = 'Prata';
//IMPRIMIR VALORES DO OBJETO. echo $carro1->ano; echo '<br />'; echo $carro1->cor;
//CHAMAR FUNCIONALIDADES DO OBJETO. echo $carro1->andar(); echo '<br />'; echo $carro1->obterInformacao();
?>
![Page 96: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/96.jpg)
UTILIZAR ATRIBUTO E MÉTODO DE OUTRA CLASSE
96
![Page 97: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/97.jpg)
HERANÇA
É ser capaz incorporar os atributos e métodos de uma classe previamente definida.
Para uma classe herdar atributos e métodos de outra classe usa-se a palavra-chave extends.
97
class A{ var $atributo1; function metodo1() { }
}class B extends A{ var $atributo2; function metodo2() { }}
$b = new B();$b->atributo2;$b->metodo2();$b->atributo1;$b->metodo1();
![Page 98: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/98.jpg)
APRENDA FAZENDO Arquivo: usuario.php
98
<?php class Usuario { var $nome; var $email; var $senha;
function inserir() { return ('Chamando método para inserir usuário.'); } function obterInformacao() { return ('Obter Informações de Usuário.'); } }?>
![Page 99: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/99.jpg)
APRENDA FAZENDO Arquivo: cliente.php
Arquivo: funcionario.php
99
<?php class Cliente extends Usuario {
}?>
<?php class Funcionario extends Usuario { var $cargo; var $salario; }?>
![Page 100: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/100.jpg)
APRENDA FAZENDO Arquivo: cliente.php
100
<?php class Cliente extends Usuario {
}
$objeto = new Cliente(); $objeto->nome = 'Junior'; $objeto->email = '[email protected]'; $objeto->senha = '123'; echo $objeto->inserir(); echo $objeto->obterInformacao();
?>
![Page 101: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/101.jpg)
APRENDA FAZENDO Arquivo: funcionario.php
101
<?php class Funcionario extends Usuario { var $cargo; var $salario; }
$objeto = new Funcionario(); $objeto->nome = 'Júnior'; $objeto->email = '[email protected]'; $objeto->senha = '123'; $objeto->cargo = 'Programador'; $objeto->salario = 3000; echo $objeto->inserir(); echo $objeto->obterInformacao();
?>
![Page 102: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/102.jpg)
FUNÇÕES DO PHP
Conheça algumas forma de importar arquivos .
102
Função Descrição
require Importar o arquivo informado para o arquivo que esta chamando a função, caso não seja encontrado o arquivo informado será exibido um Warning seguido de um Fatal error.
include Semelhante ao require porém, caso não seja encontrado o arquivo informado será exibido apenas um Warning.
require_once Identico ao require porém importa o arquivo apenas uma unica vez.
include_once Identico ao include porém importa o arquivo apenas uma unica vez.
![Page 103: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/103.jpg)
APRENDA FAZENDO - REQUIRE Arquivo: cliente.php
Arquivo: funcionario.php
103
<?php require_once('usuario.php'); class Cliente extends Usuario { ... }?>
<?php require_once('usuario.php'); class Funcionario extends Usuario { ... }?>
![Page 104: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/104.jpg)
POLIMORFISMO
104
![Page 105: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/105.jpg)
APRENDA FAZENDO Arquivo: funcionario.php
105
<?php require_once('usuario.php'); class Funcionario extends Usuario { var $cargo; var $salario;
function obterInformacao() { return ('Obter Informações de Funcionário.'); } } $objeto = new Funcionario(); $objeto->nome = 'Junior'; $objeto->email = '[email protected]'; $objeto->senha = '123'; $objeto->cargo = 'Programador'; $objeto->salario = 3000; echo $objeto->inserir(); echo $objeto->obterInformacao();?>
![Page 106: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/106.jpg)
APRENDA FAZENDO Arquivo: funcionario.php
106
<?php require_once('usuario.php'); class Funcionario extends Usuario { var $cargo; var $salario;
function obterInformacao() { return ('Obter Informações de Funcionário.<br />' . 'Nome: ' . $this->nome . '<br />' . 'E-mail: ' . $this->email . '<br />' . 'Senha: ' . $this->senha . '<br />' . 'Cargo: ' . $this->cargo . '<br />' . 'Salário: ' . $this->salario . '<br />'); } }
$objeto = new Funcionario(); ... ALIMENTAÇÃO DO OBJETO ...?>
![Page 107: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/107.jpg)
ESTUDO DE CASO Saída do arquivo: funcionario.php
Chamando método para inserir usuário.
Obter Informações de Funcionário.
Nome: Júnior
E-mail: [email protected]
Senha: 123
Cargo: Programador
Salário: 3000
Saída do arquivo: cliente.php
Chamando método para inserir usuário.
Obter Informações de Usuário.
Nome: Júnior
E-mail: [email protected]
Senha: 123
107
![Page 108: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/108.jpg)
VISIBILIDADE
Conheça as quatro formas de especificar atributos e métodos de classe.
108
Acesso Descrição
public (default) Os recursos podem ser acessados de dentro ou de fora da classe.
private Os recursos podem ser acessados apenas dentro da classe onde foi definido e não serão herdados.
protected Os recursos podem ser acessados apenas dentro da classe onde foi definido e em seus descendentes.
final Os recursos podem ser acessados de dentro ou de fora da classe, mas não podem ser sobreposto em seus descendentes.
![Page 109: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/109.jpg)
APRENDA FAZENDO
Escreva o código abaixo no arquivo visibilidade.php
109
<?php class A { public $atributo1; protected $atributo2; private $atributo3;
public function metodo1() { echo 'Chamando o método 1! <br />'; } protected function metodo2() { echo 'Chamando o método 2! <br />'; } private function metodo3() { echo 'Chamando o método 3! <br />'; } public function metodo4() { $this->atributo3; $this->metodo3(); echo 'Chamando o método 4! <br />'; } }
![Page 110: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/110.jpg)
CONTINUAÇÃO...
110
class B extends A { public function metodo5() { $this->atributo1; $this->atributo2; //$this->atributo3; //Ocorre erro porque o $atributo3 é private. $this->metodo1(); $this->metodo2(); //$this->metodo3(); //Ocorre erro porque o metodo3() é private. } }
$a = new A(); $a->atributo1; //$a->atributo2; //Ocorre erro porque o $atributo2 é protected. //$a->atributo3; //Ocorre erro porque o $atributo3 é private. $a->metodo1(); //$a->metodo2; //Ocorre erro porque o metodo2() é protected. //$a->metodo3; //Ocorre erro porque o metodo3() é private. $a->metodo4();
$b = new B(); $b->atributo1; $b->metodo1(); $b->metodo5();
?>
![Page 111: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/111.jpg)
VISIBILIDADE FINAL
Não permite sobrepor um método.
111
![Page 112: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/112.jpg)
APRENDA FAZENDO
Escreva o código abaixo no arquivo visibilidade_final.php
112
<?php class A { public $atributo1; public function metodo1() { echo 'Chamando o método 1! <br />'; } final function metodo2() { echo 'Chamando o método 2! <br />'; } }
class B extends A { //O MÉTODO metodo2 FOI DEFINIDO COMO final NA CLASSE A. public function metodo2() { echo 'Chamando o método 2! <br />'; } }
?>
![Page 113: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/113.jpg)
CONSTRUTOR
É chamado automaticamente quando um objeto é criado. Deve ser definido como público, para poder instanciar objetos
de fora da classe. Para definir métodos como construtor de uma classe, deverá
ser utilizado a palavra-chave __construct.
113
class NomeDaClasse{ public $atributo;
public function __construct() { }
}
$a = new NomeDaClasse();
![Page 114: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/114.jpg)
APRENDA FAZENDO Arquivo: construtor.php
114
<?php class A { var $cargo; var $salario;
public function __construct() { return ('Chamando o método construtor.'); } } $objeto = new Funcionario(); $objeto->nome = 'Junior'; $objeto->email = '[email protected]'; $objeto->senha = '123'; $objeto->cargo = 'Programador'; $objeto->salario = 3000; echo $objeto->inserir(); echo $objeto->obterInformacao();?>
class A { public function __construct() { return 'Chamando o método construtor! <br />'; } public function metodo1() { return 'Chamando metodo1! <br />'; } }
$a = new A(); $a->metodo1();
![Page 115: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/115.jpg)
APRENDA FAZENDO
Escreva o código abaixo no arquivo construtor.php
115
<?php class A { public function __construct() { echo 'Chamando o método construtor! <br />'; } public function metodo1() { return 'Chamando metodo1! <br />'; } }
class B { public function __construct( $mensagem ) { return 'Chamando o método construtor com a mensagem ' . $mensagem . '! <br />'; } }
$a = new A(); $a->metodo1();
$b = new B( 'Hello Construct Class' );?>
![Page 116: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/116.jpg)
ATRIBUTOS E MÉTODOS ESTÁTICOS
Um método estático não pode chamar atributos não-estáticos.
116
![Page 117: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/117.jpg)
APRENDA FAZENDO
Escreva o código abaixo no arquivo static.php
117
<?php class A { public static $atributo1 = '123 <br />'; public static function metodo1() { echo 'Chamando metodo1! <br />'; } }
//CHAMAR ESTATICAMENTE. A::metodo1(); //O método pode ou não ser static. echo A::$atributo1; //O atibuto deve ser static. echo '<br />'; //CHAMAR POR OBJETO. $a = new A(); $a->metodo1(); //O método pode ou não ser static. echo $a->atributo1; //Não é possível chamar atributo estático pelo objeto;
?>
![Page 118: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/118.jpg)
ATRIBUTOS E MÉTODOS ESTÁTICOS
Para ter acesso a atributos ou métodos estáticos dentro de uma classe, devemos utilizar a palavra-chave self::
118
![Page 119: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/119.jpg)
COMPARANDO STATIC COM NÃO-STATIC
119
![Page 120: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/120.jpg)
Desabilite (comentando) todo o script do static.php Escreva o código abaixo no arquivo static.php
120
<?php class A { public static $atributo1 = '123 <br />';
public static function metodo1() { echo self::$atributo1; echo 'Chamando metodo1! <br />'; self::metodo2(); } public static function metodo2() { echo 'Chamando metodo2! <br />'; } }
//CHAMAR ESTATICAMENTE. A::metodo1(); //O método pode ou não ser static. echo A::$atributo1; //O atibuto deve ser static.
echo '<br />'; //CHAMAR POR OBJETO. $a = new A(); $a->metodo1(); //O método pode ou não ser static. echo $a->atributo1; //Não é possível chamar atributo estático pelo objeto;
?>
![Page 121: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/121.jpg)
PADRÃO GET E SET
Utilizar os atributos da classe sempre private, excerto quando a regra de negócio não permitir.
121
class NomeDaClasse{ private $atributo;
public function getAtributo() { return ( $this->atributo ); }
public function setAtributo( $valor ) { $this->atributo = $valor; }
}
$a = new NomeDaClasse();$a->setAtributo( 'Brasil' );$a->getAtributo();
![Page 122: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/122.jpg)
APRENDA FAZENDO Escreva o código abaixo no arquivo get_set.php
122
<?php class Carro { private $ano; private $cor;
public function getAno() { return $this->ano; } public function setAno( $valor ) { $this->ano = $valor; } public function getCor() { return $this->cor; } public function setCor( $valor ) { $this->cor = $valor; } }
$a = new Carro(); //$a->ano; //Atributo privado é acessado somente dentro da classe. $a->setAno( 2009 ); echo $a->getAno() . '<br />'; $a->setCor( 'Branco' ); echo $a->getCor();
?>
![Page 123: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/123.jpg)
ESTUDO DE CASO
Implementar o Padrão Get Set nas classes: Usuario Funcionario Cliente
123
![Page 124: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/124.jpg)
ESTUDO DE CASO
Arquivo: estudo_caso_calculadora_get_set.php
124
Calculadora
- num1- num 2
+ getNum1()+ setNum1( $value )+ getNum2()+ setNum2( $value )+ somar()+ subtrair()+ multiplicar()+ dividir()
![Page 125: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/125.jpg)
ESTUDO DE CASO – ACESSAR ATRIBÚTO PRIVADO
Class Funcionario Ladrao 6% Mulher 50% Receita 100% Pretendente 2x Se nao informar ninguem pede para informar quem
que ver.
125
![Page 126: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/126.jpg)
APRENDA FAZENDO Arquivo: funcionario.php
126
<?php class Funcionario extends Usuario { private $cargo; private $salario;
public function getSalario( $interessado == 'receita' ) { if( $interessado == 'receita' ) { return( $this->salario ); } elseif( $interessado == 'ladrão' ) { return( $this->salario * 0.06 ); } ... }
} $objeto = new Funcionario(); $objeto->getSalario( ‘ladrão’ ); $objeto->email = '[email protected]'; $objeto->senha = '123'; echo $objeto->inserir(); echo $objeto->obterInformacao();
?>
![Page 127: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/127.jpg)
PROGRAMAÇÃO WEB
- Métodos GET, POST, REQUEST
![Page 128: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/128.jpg)
MÉTODO GET, POST E REQUEST
128
![Page 129: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/129.jpg)
Explicar como passar variaveis pela url
129
![Page 130: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/130.jpg)
Fazer um form_funcionario.html e enviar para class Funcionario e exibir os dados da mesma.
130
![Page 131: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/131.jpg)
ESTUDO DE CASO
131
form_calculadora.html
Número 1:
Número 2:
Operação:
Calcular
processar_form_calculadora.php
POST
![Page 132: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/132.jpg)
PHP + MYSQL – 5 HORAS
- Abrir conexão
- Executar comandos SQL
![Page 133: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/133.jpg)
FUNÇÕES DO PHP
Conheça mais algumas funções necessárias.
133
Função Descrição
mysql_connect() Abre ou reutiliza uma conexão com um servidor MySQL.
die() Construtor da linguagem equivalente a exit().
mysql_error() Retorna o texto do erro da ultima função MySQL.
mysql_select_db Seleciona um banco de dados MySQL.
![Page 134: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/134.jpg)
ABRIR CONEXÃO
134
![Page 135: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/135.jpg)
APRENDA FAZENDO
Escreva o código abaixo no arquivo conexao.php
135
<?php
//TENTAR ABRIR UMA CONEXÃO COM BANCO DE DADOS. $linkConexao = mysql_connect( 'localhost' , 'root', '‘ ) or die( 'Não foi possível se conectar ao servidor MySQL: ' . mysql_error() );
//SELECIONAR BANCO DE DADOS mysql_select_db( 'banco_1' , $linkConexao ) or die( 'Não foi possível selecionar o banco da dados.' );?>
![Page 136: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/136.jpg)
FUNÇÕES DO PHP
Conheça mais algumas funções necessárias.
136
Função Descrição
require() A instrução inclui e avalia o arquivo informado.
mysql_query() Envia uma consulta MySQL.
mysql_num_rows() Obtém o número de linhas em um resultado
![Page 137: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/137.jpg)
EXECUTAR COMANDOS SQL
137
![Page 138: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/138.jpg)
APRENDA FAZENDO
Escreva o código abaixo no arquivo executar_comandos_sql.php
138
<?php //IMPORTAR O ARQUIVO DE CONEXÃO COM O BANCO DE DADOS. require( 'conexao.php' );
//Executando a consulta SQL $comandoSQL = “INSERT INTO carro (modelo,ano,cor) VALUES (‘monza’,1993,’Preto’)”; $resultado = mysql_query( $comandoSQL );
?>
![Page 139: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/139.jpg)
$linha_afetada1 = mysql_fetch_assoc($resultado);
echo $linha_afetada1[‘modelo’] . ‘<br />’;
echo $linha_afetada1[‘cor’] . ‘<br />’;
echo $linha_afetada1[‘ano’] . ‘<br />’;
Echo ‘<br />’;
$linha_afetada2 = mysql_fetch_assoc($resultado);
echo $linha_afetada2[‘modelo’] . ‘<br />’;
echo $linha_afetada2[‘cor’] . ‘<br />’;
echo $linha_afetada2[‘ano’] . ‘<br />’;139
![Page 140: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/140.jpg)
while ( $linha_afetada = mysql_fetch_assoc($resultado) )
{
echo $linha_afetada[‘modelo’] . ‘<br />’;
echo $linha_afetada[‘cor’] . ‘<br />’;
echo $linha_afetada[‘ano’] . ‘<br />’;
echo ‘<br />’;
}
140
![Page 141: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/141.jpg)
ESTUDO DE CASO
141
form_inserir_usuario.html
Nome:
E-mail:
Senha:
Salvar
sql_inserir_usuario.php
POST
![Page 142: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/142.jpg)
ESTUDO DE CASO
Complete os get’s e set’s para todos os atributos.
142
<?php
//1. IMPORTAR CONEXÃO DO BANCO DE DADOS. require 'conexao.php'; //2. ESCREVER COMANDO SQL. $comandoSQL = "INSERT INTO usuario( nome , email , senha ) VALUES ( '" . $_POST['nome'] . "' , '" . $_POST['email'] . "' , '" . $_POST['senha'] . "' )"; //3. EXECUTAR COMANDO SQL. $resultado = mysql_query( $comandoSQL ); //4. EXIBIR MENSAGEM DE RETORNO. if ($resultado == true) { echo 'Usuário inserido com sucesso .'; } else { echo'Falha ao inserir usuário.'; }?>
sql_inserir_usuario.php
![Page 143: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/143.jpg)
LISTAR_USUARIOS.PHP
<table border=”1”>
<tr bgcolor=“#F7F7F7”>
<td width=“100”>Código</td>
<td width=“200”>Nome</td>
<td width=“60”>Editar</td>
<td width=“60”>Excluir</td>
</tr>
<tr>
<td width=“100”>1</td>
<td width=“200”>Junior</td>
<td width=“60”>Ed</td>
<td width=“60”>Ex</td>
</tr>
</table>
143
![Page 144: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/144.jpg)
<?php
require ‘conexao.php’;
$comando_sql = “SELECT * FROM usuario”;
$resultado = mysql_query( $comando_sql );
if ($resultado == false)
{
exit( ‘Falha ao recuperar usuário.’ );
}
$numLinhas = mysql_num_rows($resultado);
if ( $numLinhas == 0 )
{
exit( ‘Nenhum usuário encontrado.’ )
}
?>
144
![Page 145: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/145.jpg)
<?php while( $linha_afetada = mysql_fetch_assoc($resultado) ){ ?>
<tr>
<td width=“100”><?php echo $linha_afetada[‘id_usuario’]?></td>
<td width=“200”><?php echo $linha_afetada[‘nome’]?></td>
<td width=“60”><a href=“form_alterar_usuario.php? id=<?php echo $linha_afetada[‘id_usuario’]?>”>Ed</a></td>
<td width=“60”>
<a href=“confirmar_exclusao_usuario.php?id=<?php echo $linha_afetada[‘id_usuario’]?>”>
Ex</a></td>
</tr>
<?php } ?>
145
![Page 146: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/146.jpg)
Cria os dois arquivos de alterar e de confirmar exclusao
146
![Page 147: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/147.jpg)
Arquivo: form_alterar_usuario.php
<form action=“sql_alterar_usuario.php” method=“POST”>
Nome: <input type=“text” name=“nome” value=“123” />
<br />
E-mail: <input type=“text” name=“email” value=“123” />
<br />
Senha: <input type=“password” name=“senha” value=“123” />
<br />
<input type=“submit” value=“salvar”>
</form>
<br />
<br />
<a href=“listar_usuarios.php”>Voltar para lista</a>
147
![Page 148: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/148.jpg)
Arquivo: confirmar_exclusao_usuario.php
Deseja realmente excluir o usuario?
<br />
<br />
<a href=“sql_excluir_usuario.php?id=<?php echo $_GET[‘id’]?>”>Sim</a>
<br />
<a href=“listar_usuarios.php”>Nao</a>
148
![Page 149: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/149.jpg)
Arquivo: sql_excluir_usuario.php
<?php
require ‘conexao’;
$comandoSQL = “DELETE FROM usuario WHERE id_usuario =“ . $_GET[‘id’];
$resultado = mysql_query( $resultado );
If( $resultado == true)
{
echo ‘Usuário excluido com sucesso.’;
}
else
{
echo ‘Falha ao excluir o usuário.’;
}
?>
<br />
<a href=“listar_usuarios.php”>Voltar para lista de usuários.</a>
149
![Page 150: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/150.jpg)
Arquivo: form_alterar_usuario.php
<?php
require ‘conexao.php’;
$comandoSQL = “SELECT * FROM usuario WHERE id_usuario = ” . $_GET[‘id’];
$resultado = mysql_query( $comandoSQL );
if ($resultado == false)
{
exit(‘Falha ao executar comando SQL’);
}
$num_linhas = mysql_num_rows( $resultado );
if ( $num_linhas == 0 )
{
exit(‘’Nenhum usuário encontrado com o código informado);
}
… continua no proximo slide
150
![Page 151: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/151.jpg)
Arquivo: form_alterar_usuario.php
…continuacao…
$linha_afetada = mysql_fetch_assoc( $resultado );
?>
<form action=“sql_alterar_usuario.php” method=“POST”>
Nome: <input type=“text” name=“nome” value=“<?php echo $linha_afetada [‘nome’]?>” />
<br />
E-mail: <input type=“text” name=“email” value=“123” />
<br />
Senha: <input type=“password” name=“senha” value=“123” />
<br />
<input type=“text” name=“id” value=“<?php echo $_GET[‘id’]?>”>
<input type=“submit” value=“salvar”>
</form>
<br />
<br />
<a href=“listar_usuarios.php”>Voltar para lista</a>
151
![Page 152: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/152.jpg)
ALTERAR
152
<?php require 'conexao';
//2. ESCREVER COMANDO SQL. $comandoSQL = "UPDATE usuario SET nome = '" . $_POST['nome'] . "' , email = '" . $_POST['email'] . "' , senha = '" . $_POST['senha'] . "' WHERE id_usuario = " . $_POST['id'];
//3. EXECUTAR COMANDO SQL. $resultado = mysql_query( $comandoSQL );
//4. EXIBIR MENSAGEM DE RETORNO. if ( $resultado == true ) { echo 'Usuário alterado com sucesso.'; } else { echo 'Falha ao alterar usuário.'; }?><a href=“listar_usuarios.php”>Voltar para lista</a>
sql_alterar_usuario.php
![Page 153: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/153.jpg)
Mudar campo id para hidden
153
![Page 154: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/154.jpg)
154
form_alterar_usuario.php
listar_usuario.php
sql_alterar_usuario.php sql_excluir_usuario.php
PO
ST
sql_inserir_usuario.php
form_inserir_usuario.html
ARQUITETURA PRIMÁRIAARQUITETURA PRIMÁRIA
PO
ST
confirmar_exclusao_usuario.php
GE
T
![Page 155: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/155.jpg)
155
POST
form_alterar_usuario.html
ARQUITETURA PRIMÁRIA - OOARQUITETURA PRIMÁRIA - OO
POST
form_inserir_usuario.html
GET
listar.html
GET
confirmar_exclusao_usuario.html
Usuario.php
Qual método?
![Page 156: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/156.jpg)
156
POST
ARQUITETURA PRIMÁRIA CENTRALIZADA – OO ARQUITETURA PRIMÁRIA CENTRALIZADA – OO
POST
GET
GET
Index.php
Usuario.php
form_alterar_usuario.html
form_inserir_usuario.html
listar.html
confirmar_exclusao_usuario.html
Qual class ?Qual método?
![Page 157: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/157.jpg)
PRIMEIRO PASSO.
Criar tabela no banco de dados.
157
CREATE TABLE usuario(id_usuario int not null auto_increment,nome varchar(100),email varchar(50),senha varchar(15),primary key (id_usuario))
![Page 158: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/158.jpg)
SEGUNDO PASSO
Criar o formulário de inserção.
158
<form action="index.php?classe=Usuario&metodo=inserir" method="POST"> Nome: <input name="nome"> <br /> E-mail: <input name="email"> <br /> Senha: <input name="senha"> <br /> <input type="submit" value="Salvar"></form>
form_inserir_usuario.html
![Page 159: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/159.jpg)
TERCEIRO PASSO
Criar método na classe, para exibir o formulário de inserção
159
<?php class Usuario { public function exibirFormInserir() { require( 'form_inserir_usuario.html' ); } }?>
Usuario.php
![Page 160: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/160.jpg)
160
index.php?classe=Usuario&metodo=exibirFormInserir
![Page 161: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/161.jpg)
QUARTO PASSO
Criar e encapsular os atributos da classe.
Complete os get’s e set’s para todos os atributos. 161
<?php class Usuario { private $idUsuario; private $nome; private $email; private $senha;
public function setId( $valor ) { $this->idUsuario = $valor; } public function getId() { return( $this->idUsuario ); }
}?>
Usuario.php
![Page 162: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/162.jpg)
QUINTO PASSO Criar o método inserir.
Complete os get’s e set’s para todos os atributos.
162
<?php class Usuario { public function inserir() { //1. CRIAR UM OBJETO E ALIMENTAR COM OS DADOS DO FOMULÁRIO. $objeto = new Usuario(); $objeto->setNome( $_POST['nome' ] ); $objeto->setEmail( $_POST[ 'email' ] ); $objeto->setSenha( $_POST[ 'senha' ] );
//2. ESCREVER COMANDO SQL. $comandoSQL = "INSERT INTO carro ( nome , email , senha ) VALUES ( '" . $objeto->getNome() . "' , '" . $objeto->getEmail() . "' , '" . $objeto->getSenha() . "' )";
//3. EXECUTAR COMANDO SQL. $resultado = mysql_query( $comandoSQL );
//4. EXIBIR MENSAGEM DE RETORNO. }?>
Usuario.php
![Page 163: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/163.jpg)
PÁGINA CONTROLADORA
1 – Recuperar classe e método; 2 – Importar (require) arquivo da classe informada. 3 – Cria um objeto da classe informada. 4 – Chamar o método informado pela url, na classe importada
163
Index.php
<?php
//RECUPERAR A CLASSE E O MÉTODO INFORMADO PELO USUÁRIO ATRAVÉZ DA URL. $classe = $_GET[ 'classe' ]; $metodo = $_GET[ 'metodo' ];
//DEFINIR UMA CLASSE E UM MÉTODO PADRÃO if ( $classe == false ) $classe = 'Usuario'; if ( $metodo == false ) $metodo = 'listar';
//IMPORTAR A CLASSE INFORMADA PELA URL. require( $classe . '.php' );
//CRIAR OBJETO DA CLASSE INFORMADA. $objClasse = new $classe();
//ACESSAR O MÉTODO INFORMADO PELA URL. $objClasse->$metodo(); ?>
![Page 164: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/164.jpg)
<?php
$resultadoCategoria = Categoria::buscarTodos();
?>
<form action=“index.php?classe=produto&metodo=inserir”>
<?php if ($resultadoCategoria == true) :?>
<select name=“categoria”>
<?php while( $linha_afetada = mysql_fetch_assoc( $resultadoCategoria ) ):?>
<option value=“<?php echo $linha_afetada[‘id_categoria’]?>”><?php echo $linha_afetada[‘nome’]?></option>
<?php endwhile;?>
</select>
<?php endif;?>
164
![Page 165: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/165.jpg)
APRENDA FAZENDO
Escreva o código abaixo no arquivo executar_comandos_sql.php
165
<?php //IMPORTAR O ARQUIVO DE CONEXÃO COM O BANCO DE DADOS. require( 'conexao.php' );
//Executando a consulta SQL $comandoSQL = 'SELECT * FROM carro'; $resultado = mysql_query( $comandoSQL , $linkConexao ); //RECUPERAR QUANTIDADE DE REGISTROS ENCONTRADOS. $numeroLinhas = mysql_num_rows( $resultado ); if ( $numeroLinhas == 0 ) { exit( 'Nenhum registro encontrado.' ); } //EXIBIR NÚMERO DE REGISTROS ENCONTRADOS. echo 'Foram encontrados: ' . $numeroLinhas . ' registros.<br /><br />'; //RECUPERAR CADA LINHA OBTIDA NO RESULTADO. while ( $linhaAfetada = mysql_fetch_assoc( $resultado ) ) { echo 'Código: ' . $linhaAfetada['id_carro'] . '<br />'; echo 'Modelo: ' . $linhaAfetada['modelo'] . '<br />'; echo 'Cor: ' . $linhaAfetada['cor'] . '<br />'; echo 'Ano: ' . $linhaAfetada[‘ano'] . '<br />'; echo '<br />'; }?>
![Page 166: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/166.jpg)
REFERÊNCIA BIBLIOGRÁFICAS PHP
http://www.php.net Zend.PHP.5.Certification.Study.Guide.2006
MySQL http://www.mysql.com [acessado em 1 de maio de 2009 as 21Hrs] http://dev.mysql.com [acessado em 1 de maio de 2009 as 20Hrs] http://www.w3schools.com/sql [acessado em 1 de maio de 2009 as 21Hrs]
166
![Page 167: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/167.jpg)
APRENDA FAZENDO
Escreva o código abaixo no arquivo heranca.php Fazer um exemplo mas simples para exemplificar a herança
porque esse do transporte sera usando para exeplificar require.
167
<?php class Transporte { var $velocidade; function andar() { echo 'Transporte andando! <br /> '; } }
class Carro extends Transporte { var $cor; var $rodas; function ligar() { echo 'Carro ligado! <br /> '; }
function obterInfo() { echo 'Cor: ' . $this->cor . ' Quantidade de rodas: ' . $this->rodas . ' Velocidade Máxima: ' . $this->velocidade . '<br />‘; } }
![Page 168: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/168.jpg)
APRENDA FAZENDO
Arquivo: class_transporte.php
168
<?php class Transporte { var $velocidade; function andar() { echo 'Transporte andando! <br /> '; } }
?>
![Page 169: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/169.jpg)
APRENDA FAZENDO
Arquivo: class_carro.php
169
<?php class Carro extends Transporte { var $cor; var $rodas; function ligar() { echo 'Carro ligado! <br /> '; }
function obterInfo() { echo 'Cor: ' . $this->cor . ' Quantidade de rodas: ' . $this->rodas . ' Velocidade Máxima: ' . $this->velocidade . '<br />‘; } }
?>
![Page 170: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/170.jpg)
170
<?php class Transporte { var $velocidade; function andar() { echo 'Transporte andando! <br /> '; } }
class Carro extends Transporte { var $cor; var $rodas; function ligar() { echo 'Carro ligado! <br /> '; }
function obterInfo() { echo 'Cor: ' . $this->cor . ' Quantidade de rodas: ' . $this->rodas . ' Velocidade Máxima: ' . $this->velocidade . '<br />‘; } }
$carro1 = new Carro(); $carro1->cor = 'Vermelho'; $carro1->rodas = 4; $carro1->velocidade = 130;
$carro1->ligar(); $carro1->obterInfo(); $carro1->andar();
?>
![Page 171: PHP5 Básico](https://reader035.fdocuments.ec/reader035/viewer/2022062301/56813cb8550346895da66253/html5/thumbnails/171.jpg)
171
<?php require ( ‘class_transporte.php’ );
class Carro extends Transporte { var $cor; var $rodas; function ligar() { echo 'Carro ligado! <br /> '; }
function obterInfo() { echo 'Cor: ' . $this->cor . ' Quantidade de rodas: ' . $this->rodas . ' Velocidade Máxima: ' . $this->velocidade . '<br />‘; } }