CakeFest 2024: The Official CakePHP Conference

Básico

As variáveis no PHP são representadas por um cifrão ($) seguido pelo nome da variável. Os nomes de variável são case-sensitive (ou seja, há distinção entre maiúsculas e minúsculas).

Nomes de variável seguem as mesmas regras como outros rótulos no PHP. Um nome de variável válido inicia-se com uma letra ou sublinhado, seguido de qualquer número de letras, números ou sublinhados. Em uma expressão regular, poderia ser representado assim: ^[a-zA-Z_\x80-\xff][a-zA-Z0-9_\x80-\xff]*$

Nota: Para nosso propósito, as letras a-z, A-Z e os bytes de 127 a 255 (0x80-0xff).

Nota: $this é uma variável especial que não pode ser atribuída. Anteriormente ao PHP 7.1.0, atribuição indireta (usando variáveis variáveis) era possível.

Para informação sobre funções relacionadas a variáveis, veja a Referência de funções para variáveis.

<?php
$var
= 'Bob';
$Var = 'Joe';
echo
"$var, $Var"; // exibe "Bob, Joe"

$4site = 'not yet'; // inválido; começa com um número
$_4site = 'not yet'; // válido; começa com um sublinhado
$täyte = 'mansikka'; // válido; 'ä' é um caracter ASCII (extendido) 228
?>

Por padrão, as variáveis são sempre atribuídas por valor. Isto significa que ao atribuir uma expressão a uma variável, o valor da expressão original é copiado integralmente para a variável de destino. Isto significa também que, após atribuir o valor de uma variável a outra, a alteração de uma destas variáveis não afetará a outra. Para maiores informações sobre este tipo de atribuição, veja o capítulo em Expressões.

O PHP também oferece um outro meio de atribuir valores a variáveis: atribuição por referência. Isto significa que a nova variável simplesmente referência (em outras palavras, "torna-se um apelido para" ou "aponta para") a variável original. Alterações na nova variável afetam a original, e vice-versa.

Para atribuir por referência, simplesmente adicione um e-comercial (&) na frente do nome da variável que estiver sendo atribuída (variável de origem) Por exemplo, o trecho de código abaixo imprime 'My name is Bob' duas vezes:

<?php
$foo
= 'Bob'; // Atribui o valor 'Bob' a variável $foo
$bar = &$foo; // Referecia $foo através de $bar.
$bar = "My name is $bar"; // Altera $bar...
echo $bar;
echo
$foo; // $foo é alterada também.
?>

Uma observação importante a se fazer, é que somente variáveis nomeadas podem ser atribuídas por referência.

<?php
$foo
= 25;
$bar = &$foo; // Esta atribuição é válida.
$bar = &(24 * 7); // Inválido; referencia uma expressão sem nome.

function test()
{
return
25;
}

$bar = &test(); // Inválido.
?>

Não é necessário inicializar variáveis no PHP, contudo é uma ótima prática. Variáveis não inicializadas tem um valor padrão de tipo dependendo do contexto no qual são usadas - padrão de booleanos é false, de inteiros e ponto-flutuantes é zero, strings (por exemplo, se utilizados em echo), são definidas como vazias e arrays tornam-se um array vazio.

Exemplo #1 Valores padrões de variáveis não inicializadas

<?php
// Limpa e remove referência (sem uso de contexto) a variável; imprime NULL
var_dump($unset_var);

// Uso de booleano; imprime 'false' (Veja sobre operadores ternário para saber mais sobre a sintaxe)
echo $unset_bool ? "true\n" : "false\n";

// Uso de string; imprime 'string(3) "abc"'
$unset_str .= 'abc';
var_dump($unset_str);

// Uso de inteiro; imprime 'int(25)'
$unset_int += 25; // 0 + 25 => 25
var_dump($unset_int);

// Uso de float; imprime 'float(1.25)'
$unset_float += 1.25;
var_dump($unset_float);

// Uso de array; imprime array(1) { [3]=> string(3) "def" }
$unset_arr[3] = "def"; // array() + array(3 => "def") => array(3 => "def")
var_dump($unset_arr);

// Uso de objeto; cria novo objeto stdClass (veja http://www.php.net/manual/en/reserved.classes.php)
// Imprime: object(stdClass)#1 (1) { ["foo"]=> string(3) "bar" }
$unset_obj->foo = 'bar';
var_dump($unset_obj);
?>

Confiar no valor padrão de uma variável não inicializada é problemático no caso de incluir um arquivo em outro que usa uma variável de mesmo nome. Erros de nível E_WARNING (e anteriormente ao PHP 8.0.0, E_NOTICE) serão emitidos no caso de variáveis não inicializadas, contudo não no caso de adicionar elementos a um array não inicializado. A instrução da linguagem isset() pode ser usado para detectar se uma variável não foi inicializada.

add a note

User Contributed Notes 2 notes

up
74
jeff dot phpnet at tanasity dot com
13 years ago
This page should include a note on variable lifecycle:

Before a variable is used, it has no existence. It is unset. It is possible to check if a variable doesn't exist by using isset(). This returns true provided the variable exists and isn't set to null. With the exception of null, the value a variable holds plays no part in determining whether a variable is set.

Setting an existing variable to null is a way of unsetting a variable. Another way is variables may be destroyed by using the unset() construct.

<?php
print isset($a); // $a is not set. Prints false. (Or more accurately prints ''.)
$b = 0; // isset($b) returns true (or more accurately '1')
$c = array(); // isset($c) returns true
$b = null; // Now isset($b) returns false;
unset($c); // Now isset($c) returns false;
?>

is_null() is an equivalent test to checking that isset() is false.

The first time that a variable is used in a scope, it's automatically created. After this isset is true. At the point at which it is created it also receives a type according to the context.

<?php
$a_bool
= true; // a boolean
$a_str = 'foo'; // a string
?>

If it is used without having been given a value then it is uninitalized and it receives the default value for the type. The default values are the _empty_ values. E.g Booleans default to FALSE, integers and floats default to zero, strings to the empty string '', arrays to the empty array.

A variable can be tested for emptiness using empty();

<?php
$a
= 0; //This isset, but is empty
?>

Unset variables are also empty.

<?php
empty($vessel); // returns true. Also $vessel is unset.
?>

Everything above applies to array elements too.

<?php
$item
= array();
//Now isset($item) returns true. But isset($item['unicorn']) is false.
//empty($item) is true, and so is empty($item['unicorn']

$item['unicorn'] = '';
//Now isset($item['unicorn']) is true. And empty($item) is false.
//But empty($item['unicorn']) is still true;

$item['unicorn'] = 'Pink unicorn';
//isset($item['unicorn']) is still true. And empty($item) is still false.
//But now empty($item['unicorn']) is false;
?>

For arrays, this is important because accessing a non-existent array item can trigger errors; you may want to test arrays and array items for existence with isset before using them.
up
17
anisgazig at gmail dot com
3 years ago
clear concept of variable declaration rules and classification

variable declaration rules:

1.start with dollar sign($)
2.first letter of variable name comes from a-zA-z_
3.next letters of variable name comes from a-zA-Z0-9_
4.no space,no syntex

classification of variables:

Variable are mainly Two types
1.Predefined Variable
2.User Define Variable

Predefined Variable
There are 12 predefined variables in php 8
1.$GLOBALS
2.$_SERVER
3.$_REQUEST
4.$_FILES
5.$_ENV
6.$_SESSION
7.$_COOKIE
8.$_GET
9.$_POST
10.$http_response_header
11.$argc
12.$argv

User Define Variable
User Define variable are 3 types
1.variable scope
2.variable variables
3.reference variable

Variable Scope
variable scope are 3 types
1.local scope
2.global scope
3.static variable
To Top