PROBLEMA PHP: Codice Schema Factory di esempio non funzionante

Pubblicità

likepassion

Utente Attivo
Messaggi
19
Reazioni
0
Punteggio
25
Ciao, sto rispolverando il libro PHP 5 Guida Completa di Apogeo per ripassare php. Provando il codice a pagina 96-99 ottengo un errore, ma sono certo di aver scritto il codice in maniera identica all'esempio...

L'errore che ottengo è
Fatal error: Class name must be a valid object or a string in ... on line 75

La riga corrispondente sarebbe:
if(!isset($self::$users[$name])){

Il codice è
PHP:
<?php

  //Class

  abstract class User{

    protected $name = NULL;

    function __construct($name)
    {
      $this->name = $name;
    }

    function getName()
    {
      return $this->name;
    }

    //Metodi per i permessi
    function hasReadPermission()
    {
      return true;
    }

    function hasModifyPermission()
    {
      return false;
    }

    function hasDeletePermission()
    {
      return false;
    }

    //Metodi di personalizzazione
    function wantsFlashInterface()
    {
      return true;
    }

  }

  class GuestUser extends User{
  }

  class CustomUser extends User{
    function hasModifyPermission()
    {
      return true;
    }
  }

  class AdminUser extends User{
    function hasModifyPermission()
    {
      return true;
    }

    function hasDeletePermission()
    {
      return true;
    }

    function wantsFlashInterface()
    {
      return false;
    }
  }

  class UserFactory{
    private static $users = array("Rossi"=>"admin", "Neri"=>"guest", "Bianchi"=>"customer");

    static function Create($name)
    {
      if(!isset($self::$users[$name])){
        //Da errore perchè l'utente non esiste
      }
      switch ($self::$users[$name]){
        case "guest": return new GuestUser($name);
        case "customer": return new CustomerUser($name);
        case "admin": return new AdminUser($name);
        default: //Da errore perchè il tipo di utente non esiste
      }
    }
  }

  //Function

  function boolToStr($b)
  {
    if($b == true){
      return "Si\n";
    }else{
      return "No\n";
    }
  }

  function displayPermissions(User $obj)
  {
    print "Permessi di " . $obj->getName();
    print "Lettura: " . boolToStr($obj->hasReadyPermission());
    print "Modifica: " . boolToStr($obj->hasModifyPermission());
    print "Cancellazione: " . boolToStr($obj->hasDeletePermission());
  }

  function displayRequirements(User $obj)
  {
    if($obj->wantsFlashInterface()){
      print $obj->getName() . "vuole Flash\n";
    }
  }

  //Main

  $logins = array("Rossi", "Neri", "Bianchi");

  foreach($logins as $login){
    displayPermissions(UserFactory::Create($login));
    displayRequirements(UserFactory::Create($login));
  }

 ?>
 
Ultima modifica da un moderatore:
Pubblicità
Pubblicità
Indietro
Top