Visualizzazione dei risultati da 1 a 7 su 7
  1. #1

    Passaggio di array tra una classe e l'altra

    Salve mi sono iscritto a questo forum perchè ho un problemino con php5.

    In pratica ho due classi definite da me, la prima si occupa di gestire la connessione al database mentre la seconda di determinare la lingua del browser e, se esistente, proporre le definizioni linguistiche appropiate altrimenti quella di default.

    Lo scenario è questo:

    index.php
    Codice PHP:
    <?php

    try {
    require_once 
    'classDBLayer.php';
    require_once 
    'classLanguage.php';

    $db DBLayer ($localhost$username$password$porta)
    $sql_query ìselect from language';
    $lang = $db->DBQuery($sql_query);
    }
    catch (Exception  $e) {      
            $e->getMessage(); 
    }

    ?>
    classLanguage.php
    Codice PHP:
    <?php

    class Language {
        
            private 
    $browserAcceptLanguage;
            private 
    $url;
            private 
    $defaultDir;
            
            public function 
    __construct () {    
                    
    $this->browserAcceptLanguage substr($_SERVER['HTTP_ACCEPT_LANGUAGE'],,2);
                    
    $this->url _LOGIN_ADMIN DS 'language' DS;
                    
    $this->defaultDir 'it_IT';
                    
    self::getDir();
            }
            
            public function 
    getDir() {
                    while (list (
    $key$value)  = each ($lang)) {
                        if (
    $key == $this->browserAcceptLanguage) {
                            
    $langDir $this->url $value;
                                if (
    is_dir($langDir)) {
                                    
    setcookie ('lang'$langDir);    
                                    } else {
                                    
    $langDir $this->url $this->defaultDir;
                                    if (
    is_dir($langDir)) {
                                        
    setcookie ('lang'$langDir);
                                    } else {
                                        echo 
    'Nessna lingua presente. Sito bloccato';
                                        exit();
                                    }
                                }
                        }
                    }
                }
        
    }

    ?>
    classDBLayer.php
    Codice PHP:
    <?php

    class DBLayer {
            
            
    /**
             *
             * Dati di connessione
             *
             */
            
    private $dbhost;        // @string   - nome del server  
            
    private $dbuname;        // @string   - utente del server
            
    private $dbupass;        // @string   - password del server
            
    private $dbname;        // @string   - nome del database
            
    private $dbport;        // @num      - porta in cui Ã¨ in ascolto mysql
            
            /**
             *
             * Opzioni database
             *
             * Permette di scegliere il metedo di gestire i caratteri dannosi 
             * nel database
             * 
             * private $sanitize int
             * 0 - nessuna gestione ... qualsiasi carattere verrÃ_ inserito nel database
             * 1 - funzione mysql_real_escape_string
             * 2 - sostituzine delle entitÃ_ html
             *
             */
            
    private $sanitize 1
            
            
    /**
             *
             * Gestione errori
             *
             */
            
    private $log_file "mysql_error.log";        // @string target file for error
            
    private $display_error 0;                    // @int 0 die quit mode, 1 die verbose mode
            
    private $log_errors 1;                    // @int 0 not log, 1 log
            
            /**
             *
             * Constuct
             * Access: public, return void
             *
             */
            
    public function __construct($dbhost$dbuname$dbupass$dbname$dbport) {
                    
    $this->dbhost =  $dbhost;
                    
    $this->dbuname $dbuname;
                    
    $this->dbupass $dbupass;
                    
    $this->dbname =  $dbname;
                    
    $this->dbport =  $dbport;
                    
    $this->link_id mysql_connect ($this->dbhost$this->dbuname$this->dbupass$this->dbport);
                            if (!
    $this->link_id) {
                                    throw new 
    Exception($this->DBError(mysql_error(), mysql_errno()));
                                    exit();
                            } 
                            
                    
    $this->link_db mysql_select_db ($this->dbname$this->link_id);
                            if (!
    $this->link_db) {
                                    throw new 
    Exception($this->DBError(mysql_error(), mysql_errno()));
                                    exit();
                            }
            } 
    // end __construct()
            
            /**
             *
             * Gestione degli errori. A seconda di come viene configurata permette di salvare gli errori in
             * file di testo.
             */
            
    public function DBError($mysql_error$mysql_errno) {
                
                    if (
    $this->log_errors) {
                            if (!
    $fp fopen($this->log_file'a')) {
                                    if (
    $this->display_errors) {
                                            die (
    "Error Handler: Impossibile leggere il file " $this->log_file);
                                    }
                            }
                    
                            
    $err "Date of Error: " date("d F Y - H:i:s") . "\n" 
                                 
    "Error Message: " $mysql_error "\n" 
                                 
    "Error Number : " $mysql_errno "\n"
                                 
    "IP From Error: " $_SERVER['REMOTE_ADDR'] . "\n\n";
                            if(!
    fwrite($fp,$err)) {
                                    if (
    $this->display_errors) {
                                            die (
    "Error Handler: Impossibile scrivere nel file " $this->log_file);
                                    }
                            }
                    
                            
    fclose($fp);
                    }
                    if(
    $this->display_errors) {
                            die (
    $error);
                    }
                    
            } 
    // end DBError()
                    
                    
            /**
             *
             * Query nel database
             *
             */
            
    public function DBQuery($sql_query) {
                    if (!
    $this->result mysql_query ($sql_query)) {
                            throw new 
    Exception($this->DBError(mysql_error(), mysql_errno()));
                    }
                    
                    return 
    $this->result;
                    
            } 
    // end DBQuery()
            
            /**
             *
             * mysql_num_rows estraggo il numero di righe in un set di risultati
             *
             */
            
    public function DBNumRows($result) {
                    if (!
    $this->rows mysql_num_rows($this->result)) {
                                    throw new 
    Exception($this->DBError(mysql_error(), mysql_errno()));
                    }
                    
            
                    return 
    $this->rows;
            } 
    // end DBNumRows()
            
            /**
             *
             * mysql_num_fields estraggo il numero di colonne in un set di risultati
             *
             */
            
    public function DBNumFields($result) {
                    if (!
    $this->fields mysql_num_fields($this->result)) {
                                    throw new 
    Exception($this->DBError(mysql_error(), mysql_errno()));
                    }
                    
                    return 
    $this->fields;
            } 
    // end DBNumFields()
            
            /**
             *
             * FetchNextRow
             * 
             * Visualizzazione dei dati contenuti nel database, accetta 3 parametri
             *
             * $result = puntatore al set di risultati
             * $val = assoc (MYSQL_ASSOC)
             *        num   (MYSQL_NUM)
             *        both  (MYSQL_BOTH)
             *
             */
            
    public function FetchNextRow($result$val) {                
                    switch (
    $val) {
                            case 
    assoc
                                    if (
    $row mysql_fetch_array($this->resultMYSQL_ASSOC)) {
                                            
    $this->currentRow =& $row;
                                            
    $this->EOF false;
                                    } else {
                                            
    $this->EOF true;
                                    }
                    
                                            return 
    $row;
                                            break;
                                            
                            case 
    num
                                    if (
    $row mysql_fetch_array($this->resultMYSQL_NUM)) {
                                            
    $this->currentRow =& $row;
                                            
    $this->EOF false;
                                    } else {
                                            
    $this->EOF true;
                                    }
                    
                                            return 
    $row;
                                            break;
                                            
                            case 
    both
                                    if (
    $row mysql_fetch_array($this->resultMYSQL_BOTH)) {
                                            
    $this->currentRow =& $row;
                                            
    $this->EOF false;
                                    } else {
                                            
    $this->EOF true;
                                    }
                    
                                            return 
    $row;
                                            break;
                                            
                             default:
                                            break;
                                            
                    } 

            } 
    // end FetchNextRow()
            
            /**
             *
             * mysql_insert_id id auto increment generato dal ultima query insert
             *
             */
            
    public function DBLastId($result) {
                    if (!
    $this->lastid mysql_insert_id($this->link_id)) {
                                    throw new 
    Exception($this->DBError(mysql_error(), mysql_errno()));
                    }
                    
                    return 
    $this->lastid;
            } 
    // end DBLastId()
            
            /**
             *
             * DBCheck
             * Questo metodo prende in input una stringa e aggiunge gli slash dove necessario
             * 
             * parms string string
             *
             */
            
    public function DBCheck($data) {
                
                    if (!
    get_magic_quotes_gpc()) {
                            
    $data stripslashes(trim($data));        
                    }
                      
                    if (!
    is_numeric($data)) {
                            if (
    $this->sanitize == 1) {
                                    
    $data mysql_real_escape_string($data);
                            } elseif (
    $this->sanitize == 2) {
                                    
    $data str_replace("'","&apos;",mysql_real_escape_string($data));
                            } 
                    }
                    
                    return 
    $data;
                    
            } 
    // end method DBCheck()
            
            /**
             *
             * Libera la memoria usata dai set di risultati e chiama il metodo di disconnessione 
             *
             */     
            
    public function __destruct() {
                    if (
    is_resource($this->query)) {
                            
    mysql_free_result($this->query);
                    }
                    
    $this->DBClose();            
            } 
    // end __desctruct()
            
            /** 
             *
             * Chiude le connessione al database
             *
             */
            
    public function DBClose() {
                    if (
    $this->link_id) {
                            if (!
    mysql_close($this->link_id)) {
                                throw new 
    Exception ($this->DBError(mysql_error(), mysql_errno()));
                            } 
                    }
            } 
    // end DBClose()

    }

    ?>
    database
    Codice PHP:
    CREATE TABLE IF NOT EXISTS `language` (
      `
    suffixvarchar(10NOT NULL DEFAULT '' COMMENT 'langSuffix',
      `
    langvarchar(10NOT NULL DEFAULT '' COMMENT 'langIdentifier'
    ENGINE=MyISAM DEFAULT CHARSET=latin1;

    --
    -- 
    Dump dei dati per la tabella `language`
    --

    INSERT INTO `language` (`suffix`, `lang`) VALUES
    ('it''it_IT'),
    (
    'en''en_GB'); 
    La domanda è come faccio a dare in pasto alla classLanguage l'array $lang contenenti il set di risultati della query sul database ?

    Grazie per le risposte

  2. #2
    e se su index.php provassi questo?

    Codice PHP:
    <?php     try {   require_once 'classDBLayer.php';  

     require_once 
    'classLanguage.php';   

      
    $db DBLayer ($localhost$username$password$porta)   $sql_query ìselect from language';   $lang = $db->DBQuery($sql_query);  
    globals $lang; }   catch (Exception  $e) {                 $e->getMessage();   }     ?>

    impostando $lang come globals dovresti riuscire a passarla anche alle classi

  3. #3
    Niente da fare, passando con global sono sempre al

    codice:
    Warning: Variable passed to each() is not an array or object

  4. #4
    Codice PHP:
    class DBLayer extends Language

  5. #5
    Originariamente inviato da System
    Codice PHP:
    class DBLayer extends Language
    ci stavo pensando in questo momento ... e infatti funziona

  6. #6

  7. #7
    Riesumo un secondo il post.

    La soluzione di estendere la classe linguaggio funziona ma fino ad un certo punto. Avendo le impostazioni della lingua dentro al database, difatti, prima devo caricare la classe DBLayer poi la classe Language e come previsto nel contesto del programma che sto scrivendo non funziona più niente dato che è impossibile che la classe Language elabori dei dati in arrivo dal db senza che in precedenda siano stati estratti; spero di non essermi spiegato con i piedi.

    Qualche suggerimento ?

Permessi di invio

  • Non puoi inserire discussioni
  • Non puoi inserire repliche
  • Non puoi inserire allegati
  • Non puoi modificare i tuoi messaggi
  •  
Powered by vBulletin® Version 4.2.1
Copyright © 2025 vBulletin Solutions, Inc. All rights reserved.