|
Home -> Manuali e Tutorials -> Guida PHP -> Classi (3/3)
Scarica il tutorial | Stampa il tutorial | Cerca nel sito
CLASSI PHP
Variabile o metodo Statico
Di seguito è riportato un esempio di variabile statica:
<?php
class foo
{
static $my_static = 5;
public $my_prop = "asd";
}
print foo::$my_static;
$obj = new foo;
print $obj->my_prop;
?>
|
La differenza quindi tra una variabile statica ed una non, è che è possibile accederci senza istanziare la classe, ma usando i :: .
Di seguito, invece, è mostrato un esempio di metodo statico, la cui definizione è la stessa:
<?php
class foo
{
public static function my_static_method()
{
...
}
}
print foo::$my_static;
$obj = new foo;
print $obj->my_prop;
?>
|
Eccezioni
La gestione delle Eccezioni non è presente in PHP 4, ma è presente nella versione 5, che introduce tale concetto nello stesso modo di quello presente ad esempio in Java. Viene supportata la clausola "catch all" ma non la "finally". L'eccezione può essere gestita anche nei blocchi catch, esattamente come in Java; ma se questa non viene gestita in alcun modo, l'applicazione va in eccezione. Di seguito è riportato il codice php necessario per gestire una generica eccezione:
<?php
try
{
$error = 'throw questo errore';
throw new Exception($error);
// Il codice che segue ad una eccezione non viene eseguito.
echo 'Mai eseguita!';
}
catch (Exception $e)
{
echo 'Eccezione trovata: ', $e->getMessage(), "\n";
}
// Continua l'esecuzione dell'applicazione
echo 'Hello World';
?>
|
Il blocco Try viene usato per gestire parte del codice php dell'applicazione che potrebbe generare un'eccezione, che viene però riportata e quindi gestita dal blocco seguente catch attraverso la parola chiave throw; in genere il blocco catch printa il tipo di errore. Nel blocco try, le istruzioni che seguono la riga del throw, non vengono eseguite nel caso in cui si genera un'eccezione.
E' sempre possibile definire una calsse madre Exception contenente metodi generici per la gestione di errori:
<?php
class Exception
{
protected $message = 'Unknown exception'; // exception message
protected $code = 0; // user defined exception code
protected $file; // source filename of exception
protected $line; // source line of exception
function __construct($message = null, $code = 0);
final function getMessage(); // message of exception
final function getCode(); // code of exception
final function getFile(); // source filename
final function getLine(); // source line
final function getTrace(); // an array of the backtrace()
final function getTraceAsString(); // formated string of trace
/* Overrideable */
function __toString(); // formated string for display
}
?>
|
ed una classe figlia, MyException, che estenda quella madre:
<?php
class MyException extends Exception
{
// Redefine the exception so message isn't optional
public function __construct($message, $code = 0) {
// some code
// make sure everything is assigned properly
parent::__construct($message, $code);
}
// custom string representation of object */
public function __toString() {
return __CLASS__ . ": [{$this->code}]: {$this->message}\n";
}
public function customFunction() {
echo "A Custom function for this type of exception\n";
}
}
?>
|
Di seguito è riportato il codice di una classe esempio per testare le eccezioni di cui sopra:
<?php
class TestException
{
public $var;
const THROW_NONE = 0;
const THROW_CUSTOM = 1;
const THROW_DEFAULT = 2;
function __construct($avalue = self::THROW_NONE)
{
switch ($avalue) {
case self::THROW_CUSTOM:
// throw custom exception
throw new MyException('1 is an invalid parameter', 5);
break;
case self::THROW_DEFAULT:
// throw default one.
throw new Exception('2 isnt allowed as a parameter', 6);
break;
default:
// No exception, object will be created.
$this->var = $avalue;
break;
}
}
}
// Example 1
try {
$o = new TestException(TestException::THROW_CUSTOM);
} catch (MyException $e) { // Will be caught
echo "Caught my exception\n", $e;
$e->customFunction();
} catch (Exception $e) { // Skipped
echo "Caught Default Exception\n", $e;
}
// Continue execution
var_dump($o);
echo "\n\n";
// Example 2
try {
$o = new TestException(TestException::THROW_DEFAULT);
} catch (MyException $e) { // Doesn't match this type
echo "Caught my exception\n", $e;
$e->customFunction();
} catch (Exception $e) { // Will be caught
echo "Caught Default Exception\n", $e;
}
// Continue execution
var_dump($o);
echo "\n\n";
// Example 3
try {
$o = new TestException(TestException::THROW_CUSTOM);
} catch (Exception $e) { // Will be caught
echo "Default Exception caught\n", $e;
}
// Continue execution
var_dump($o);
echo "\n\n";
// Example 4
try {
$o = new TestException();
} catch (Exception $e) { // Skipped, no exception
echo "Default Exception caught\n", $e;
}
// Continue execution
var_dump($o);
echo "\n\n";
?>
|
Torna su | Indice Guida | Pagina << 19 >>
|