problema: dichiarare e richiamare variabili all'interno di una classe

pino83

Nuovo Utente
12 Giu 2012
2
0
0
Ciao a tutti, ho un problema nel dichiarare variabili all'interno di una classe.
Mi spiego:
ho creato una pagina 'ricerca_dati.php' contenente il seguente codice
PHP:
<!DOCTYPE html> 
<html> 
      <head> 
                  [......] 
      </head> 
          <body> 
              <header> 
                    <h1>Ricerca albo</h1> 
            </header> 
          <?php 
           
        $titolo = htmlentities($_GET["titolo"]); 
        $titolo = mysql_real_escape_string($titolo); 
         
        $self = htmlentities($_SERVER['PHP_SELF']); 
        $form = ' 
            <form action="'.$self.'" method="GET"> 
              <fieldset> 
                <legend>Cerca per titolo (o parte di esso)</legend> 
                <label for="titolo"> 
                  Titolo:<input type="text" id="titolo" name="titolo"> 
                </label> 
                <input type="submit" value="Ricerca"> 
              </fieldset> 
              <input type="submit" value="Ricerca"> 
               
            </form> 
            '; 
/**********QUI INCLUDO IL FILE CLASSE_RICERCA.PHP**********/ 
          require("classe_ricerca.php"); 
          $Ricerca = new Ricerca(); 
          if($titolo === '') 
          { 
           echo $form; 
         } 
         else if($titolo != '') 
         { 
          $Ricerca->titolo(); 
          echo $form; 
         } 
                  ?> 
      </body> 
</html>
il file 'classe_ricerca.php' contiene
PHP:
<?php 
class Ricerca 
{ 
/***********METODO COSTRUTTORE***********/  
 function Ricerca() 
 { 
  require_once("db_login_2.php"); 
  $connect = mysql_connect($db_host, $db_user, $db_password); 
  if(!$connect) 
  { 
    die(mysql_error());   
  } 
  else{echo "connessione riuscita</br>";} 
  $data = mysql_select_db($db_database); 
  if(!$data) 
  { 
    die(mysql_error()); 
  } 
  else{echo "database ".strtoupper($db_database)." selezionato</br>";} 
 } 
/***********METODO DI RICERCA PER TITOLO***********/  
 function titolo() 
 { 
  $titolo = htmlentities($_GET["titolo"]); 
  $titolo = mysql_real_escape_string($titolo); 
  $cerca = "SELECT numeri,titoli,nome_testi,cognome_testi, 
            nome_disegni,cognome_disegni,tipo 
            FROM numeri 
            JOIN testi ON (numeri.id_testi=testi.id_testi) 
            JOIN disegni ON (numeri.id_disegni=disegni.id_disegni) 
            JOIN stampa ON (numeri.id_stampa=stampa.id_stampa) 
            WHERE numeri.titoli LIKE '%$titolo%' 
            ORDER BY numeri.numeri"; 
  $result = mysql_query($cerca); 
  if(!$result) 
  { 
   die(mysql_error()); 
  } 
  $albi = mysql_num_rows($result); 
/********DICHIARO LE MIE 3 VARIABILI DIRETTAMENTE ALL'INTERNO DEL METODO********/ 
  $magg_uno = " 
              <table> 
                  <tr> 
                       <th colspan='5'> 
                RICERCA PER TITOLO EFFETTUATA<br /> 
                Parametro di ricerca: <strong class='trovato'>$titolo<br /> 
                $albi albi trovati</strong> 
             </th> 
                  </tr> 
                  <tr> 
                       <th>Numero</th> 
                    <th>Titolo</th> 
                    <th>Testi</th> 
                    <th>Disegni</th> 
                    <th>Stampa</th> 
                  </tr>"; 
  $uno = " 
              <table> 
              <tr> 
                   <th colspan='5'> 
                RICERCA PER TITOLO EFFETTUATA<br /> 
                    Parametro di ricerca: <strong class='trovato'>$titolo<br /> 
                $albi albo trovato</strong> 
                 </th> 
              </tr> 
              <tr> 
                   <th>Numero</th> 
                <th>Titolo</th> 
                <th>Testi</th> 
                <th>Disegni</th> 
                <th>Stampa</th> 
              </tr>"; 
  $zero = " 
              <table> 
              <tr> 
                   <th colspan='5'> 
                RICERCA PER TITOLO EFFETTUATA<br /> 
                Parametro di ricerca: <strong class='trovato'>$titolo<br /> 
                Spiacente, nessuna corrispondenza</strong> 
                 </th> 
              </tr> 
              <tr> 
                   <th>Numero</th> 
                <th>Titolo</th> 
                <th>Testi</th> 
                <th>Disegni</th> 
                <th>Stampa</th> 
              </tr>"; 
  if($albi > 1) 
  { 
   echo $magg_uno; 
  } 
  else if($albi === 1) 
  { 
   echo $uno; 
  } 
  else 
  { 
   echo $zero; 
  } 
   
  while($row = mysql_fetch_array($result, MYSQL_ASSOC)) 
  { 
   $tit = strtoupper($row["titoli"]); 
   $num = $row["numeri"]; 
   $tes1 = $row["nome_testi"]; 
   $tes2 = $row["cognome_testi"]; 
   $dis1 = $row["nome_disegni"]; 
   $dis2 = $row["cognome_disegni"]; 
   $sta = $row["tipo"]; 
     
   echo "<tr>"; 
   echo "<td>$num</td>"; 
   echo "<td class='trovato'>$tit</td>"; 
   echo "<td>$tes1 $tes2</td>"; 
   echo "<td>$dis1 $dis2</td>"; 
   echo "<td>$sta</td>"; 
   echo "</tr>"; 
  } 
  echo "</table>"; 
  mysql_close($connect); 
 } 
} 
 ?>
e fin qui tutto ok, quando accedo a 'ricerca_dati.php' dal browser tutto funziona alla perfezione.
Poi però ho pensato di modificare la classe in questo modo
PHP:
<?php 
class Ricerca 
{ 
/********DICHIARO SUBITO LE 3 VARIABILI IN MODO CHE SIANO COMUNI A TUTTI I METODI DELLA CLASSE********/ 
  public $magg_uno = " 
              <table> 
                  <tr> 
                       <th colspan='5'> 
                RICERCA PER TITOLO EFFETTUATA<br /> 
                Parametro di ricerca: <strong class='trovato'>$titolo<br /> 
                $albi albi trovati</strong> 
             </th> 
                  </tr> 
                  <tr> 
                       <th>Numero</th> 
                    <th>Titolo</th> 
                    <th>Testi</th> 
                    <th>Disegni</th> 
                    <th>Stampa</th> 
                  </tr>"; 
  public $uno = " 
              <table> 
              <tr> 
                   <th colspan='5'> 
                RICERCA PER TITOLO EFFETTUATA<br /> 
                    Parametro di ricerca: <strong class='trovato'>$titolo<br /> 
                $albi albo trovato</strong> 
                 </th> 
              </tr> 
              <tr> 
                   <th>Numero</th> 
                <th>Titolo</th> 
                <th>Testi</th> 
                <th>Disegni</th> 
                <th>Stampa</th> 
              </tr>"; 
  public $zero = " 
              <table> 
              <tr> 
                   <th colspan='5'> 
                RICERCA PER TITOLO EFFETTUATA<br /> 
                Parametro di ricerca: <strong class='trovato'>$titolo<br /> 
                Spiacente, nessuna corrispondenza</strong> 
                 </th> 
              </tr> 
              <tr> 
                   <th>Numero</th> 
                <th>Titolo</th> 
                <th>Testi</th> 
                <th>Disegni</th> 
                <th>Stampa</th> 
              </tr>"; 
/***********METODO COSTRUTTORE***********/  
 function Ricerca() 
 { 
  require_once("db_login_2.php"); 
  $connect = mysql_connect($db_host, $db_user, $db_password); 
  if(!$connect) 
  { 
    die(mysql_error());   
  } 
  else{echo "connessione riuscita</br>";} 
  $data = mysql_select_db($db_database); 
  if(!$data) 
  { 
    die(mysql_error()); 
  } 
  else{echo "database ".strtoupper($db_database)." selezionato</br>";} 
 } 
/***********METODO DI RICERCA PER TITOLO***********/  
 function titolo() 
 { 
  $titolo = htmlentities($_GET["titolo"]); 
  $titolo = mysql_real_escape_string($titolo); 
  $cerca = "SELECT numeri,titoli,nome_testi,cognome_testi, 
            nome_disegni,cognome_disegni,tipo 
            FROM numeri 
            JOIN testi ON (numeri.id_testi=testi.id_testi) 
            JOIN disegni ON (numeri.id_disegni=disegni.id_disegni) 
            JOIN stampa ON (numeri.id_stampa=stampa.id_stampa) 
            WHERE numeri.titoli LIKE '%$titolo%' 
            ORDER BY numeri.numeri"; 
  $result = mysql_query($cerca); 
  if(!$result) 
  { 
   die(mysql_error()); 
  } 
  $albi = mysql_num_rows($result); 

  if($albi > 1) 
  { 
   echo $this->magg_uno; 
  } 
  else if($albi === 1) 
  { 
   echo $this->uno; 
  } 
  else 
  { 
   echo $this->zero; 
  } 
   
  while($row = mysql_fetch_array($result, MYSQL_ASSOC)) 
  { 
   $tit = strtoupper($row["titoli"]); 
   $num = $row["numeri"]; 
   $tes1 = $row["nome_testi"]; 
   $tes2 = $row["cognome_testi"]; 
   $dis1 = $row["nome_disegni"]; 
   $dis2 = $row["cognome_disegni"]; 
   $sta = $row["tipo"]; 
     
   echo "<tr>"; 
   echo "<td>$num</td>"; 
   echo "<td class='trovato'>$tit</td>"; 
   echo "<td>$tes1 $tes2</td>"; 
   echo "<td>$dis1 $dis2</td>"; 
   echo "<td>$sta</td>"; 
   echo "</tr>"; 
  } 
  echo "</table>"; 
  mysql_close($connect); 
 } 
} 
 ?>
perché ho pensato che così facendo, volendo in futuro creare altri metodi di ricerca, non avrei dovuto ridefinire le 3 variabili all'interno di ogni metodo, ma basta richiamarle con $this. Invece ciò che ottengo accedendo a 'ricerca_dati.php' dal browser è una pagina bianca ad eccezione del codice html inserito prima del php, ovvero fino a
HTML:
<!DOCTYPE html> 
<html> 
      <head> 
                  [......] 
      </head> 
          <body> 
              <header> 
                    <h1>Ricerca albo</h1> 
            </header>
per il resto vuoto totale. Sicuramente sbaglio qualcosa nella dichiarazione delle variabili, ma non riesco a capire cosa....
Grazie per l'attenzione.
 

alessandro1997

Utente Attivo
6 Ott 2009
5.302
1
0
26
Roma
alessandro1997.netsons.org
Stai facendo un errore piuttosto comune a chi si addentra per la prima volta nel mondo dell'OOP: creare una classe quando non serve. Ricordati che una classe non è solo un modo per raggruppare codice che ha lo stesso scopo, ma deve trattarsi di un'entità viva, palpabile. Non puoi creare una classe Ricerca, perché la ricerca è un'azione, non un'entità. Al massimo puoi creare una classe Cercatore (terribile usare l'Italiano in un linguaggio di programmazione), ma dovrà essere strutturata in maniera completamente diversa da come stai facendo tu, e dovranno esserci altre classi che lavorano con essa.

Ti consiglio di leggere un manuale sulla programmazione ad oggetti, su come e quando dev'essere usata.
 

pino83

Nuovo Utente
12 Giu 2012
2
0
0
Hai ragione, ci ho riflettuto e in effetti non aveva molto senso usare una classe in quel caso. Ho riscritto il codice in procedurale, eliminando del tutto il file con la classe e ho ridotto le funzioni a due, una di connessione e selezione db e una di ricerca. Funziona benissimo. Volevo un tuo parere sull'eleganza (o non eleganza) del mio script.
PHP:
<?php
$titolo = htmlentities($_GET["titolo"]);
$numero = htmlentities($_GET["numero"]);
$testi = htmlentities($_GET["testi"]);
$disegni = htmlentities($_GET["disegni"]);
$self = htmlentities($_SERVER['PHP_SELF']);
$form = '
	<div>
	  <div>
	    <form action="'.$self.'" method="GET">
	      <div>
	        <fieldset>
	          <legend>Cerca per titolo</legend>
	          <label for="title">
			    Titolo<input type="text" id="title" name="title">
			  </label>
			  <input type="submit" class="submit" value="Ricerca">
	        </fieldset>
		  </div>
		  <div>
		    <fieldset>
			  <legend>Cerca per numero</legend>
	 		  <label for="number">
			    Numero<input type="number" min="1" id="number" name="number">
	          </label>
			  <input type="submit" class="submit" value="Ricerca">
	        </fieldset>
	      </div>
	 	  <div>
		    <fieldset>
			  <legend>Cerca per autori</legend>
			  <label for="text">
			    Scrittore<input type="text" id="text" name="text">
	          </label>
			  <label for="draw">
			    Disegnatore<input type="text" id="draw" name="draw">
	          </label>
			  <input type="submit" class="submit" value="Ricerca">
	        </fieldset>
	      </div>
	    </form>
	  </div>
	  <div>
	    <p>In questa sezione è possibile effettuare ricerche selettive in base a differenti paramtri di ricerca.
	    </p>
	  </div>
	</div>
	';
/***********METODO DI CONNESSIONE A MYSQL E SELEZIONE DB***********/ 
function connect()
{
  require_once("db_login_2.php");
  $connect = mysql_connect($db_host, $db_user, $db_password);
  if(!$connect)
  {
    die(mysql_error());  
  }
  $data = mysql_select_db($db_database);
  if(!$data)
  {
    die(mysql_error());
  }
}
/***********METODO DI RICERCA***********/ 
function search($x, $y)
{
  if($x == $_GET['titolo'])
  {
  $x = trim($x);
  $x = mysql_real_escape_string($x);
  $search = "SELECT *
			FROM numeri
			JOIN testi ON (numeri.id_testi=testi.id_testi)
			JOIN disegni ON (numeri.id_disegni=disegni.id_disegni)
			JOIN stampa ON (numeri.id_stampa=stampa.id_stampa)
			WHERE numeri.titoli LIKE '%$x%'
			ORDER BY numeri.numeri";
  }
  else if($x == $_GET['numero'])
  {
  $x = trim($x);
  $x = mysql_real_escape_string($x);
  $search = "SELECT *
			FROM numeri
			JOIN testi ON (numeri.id_testi=testi.id_testi)
			JOIN disegni ON (numeri.id_disegni=disegni.id_disegni)
			JOIN stampa ON (numeri.id_stampa=stampa.id_stampa)
			WHERE numeri.numeri LIKE '%$x%'";
  }
  else if($x == $_GET['testi'] && $y === null)
  {
  $x = trim($x);
  $x = mysql_real_escape_string($x);
  $search = "SELECT *
			FROM numeri
			JOIN testi ON (numeri.id_testi=testi.id_testi)
			JOIN disegni ON (numeri.id_disegni=disegni.id_disegni)
			JOIN stampa ON (numeri.id_stampa=stampa.id_stampa)
			WHERE testi.cognome_testi LIKE '%$x%'
			ORDER BY numeri.numeri";
  }
  else if($x == $_GET['disegni'] && $y === null)
  {
  $x = trim($x);
  $x = mysql_real_escape_string($x);
  $search = "SELECT *
			FROM numeri
			JOIN testi ON (numeri.id_testi=testi.id_testi)
			JOIN disegni ON (numeri.id_disegni=disegni.id_disegni)
			JOIN stampa ON (numeri.id_stampa=stampa.id_stampa)
			WHERE disegni.cognome_disegni LIKE '%$x%'
			ORDER BY numeri.numeri";
  }
  else if($y == $_GET['disegni'])
  {
  $x = trim($x);
  $x = mysql_real_escape_string($x);
  $y = trim($y);
  $y = mysql_real_escape_string($y);
  $search = "SELECT *
			FROM numeri
			JOIN testi ON (numeri.id_testi=testi.id_testi)
			JOIN disegni ON (numeri.id_disegni=disegni.id_disegni)
			JOIN stampa ON (numeri.id_stampa=stampa.id_stampa)
			WHERE testi.cognome_testi LIKE '%$x%' && disegni.cognome_disegni LIKE '%$y%'
			ORDER BY numeri.numeri";
  }
  $result = mysql_query($search);
  if(!$result)
  {
   die(mysql_error());
  }
  $albi = mysql_num_rows($result);
  $magg_uno = "<table id='ricerca'>
       		   <tr>
       		   	 <th colspan='5'>
					   RICERCA TERMINATA<br />
					   Parametri di ricerca: <strong class='trovato'>$x $y<br />
					   $albi albi trovati</strong>
				 </th>
       		   </tr>
       		   <tr>
       		   	 <th>Numero</th>
       			 <th>Titolo</th>
       			 <th>Testi</th>
       			 <th>Disegni</th>
       			 <th>Stampa</th>
       		   </tr>";
  $uno = "<table id='ricerca'>
   		   <tr>
   		   	 <th colspan='5'>
					   RICERCA TERMINATA<br />
					   Parametri di ricerca: <strong class='trovato'>$x $y<br />
					   $albi albo trovato</strong>
				 </th>
   		   </tr>
   		   <tr>
   		   	 <th>Numero</th>
   			 <th>Titolo</th>
   			 <th>Testi</th>
   			 <th>Disegni</th>
   			 <th>Stampa</th>
   		   </tr>";
  $zero = "<table id='ricerca'>
   		   <tr>
   		   	 <th colspan='5'>
					   RICERCA TERMINATA<br />
					   Parametri di ricerca: <strong class='trovato'>$x $y<br />
					   Spiacente, nessuna corrispondenza</strong>
				 </th>
   		   </tr>";
  if($albi > 1)
  {
   echo $magg_uno;
  }
  else if($albi === 1)
  {
   echo $uno;
  }
  else
  {
   echo $zero;
  }
  
  while($row = mysql_fetch_array($result, MYSQL_ASSOC))
  {
   $tit = strtoupper($row["titoli"]);
   $num = $row["numeri"];
   $tes1 = $row["nome_testi"];
   $tes2 = $row["cognome_testi"];
   $dis1 = $row["nome_disegni"];
   $dis2 = $row["cognome_disegni"];
   $sta = $row["tipo"];
	
   echo "<tr>";
   echo "<td>$num</td>";
   echo "<td class='trovato'>$tit</td>";
   echo "<td>$tes1 $tes2</td>";
   echo "<td>$dis1 $dis2</td>";
   echo "<td>$sta</td>";
   echo "</tr>";
  }
  echo "</table>";
  mysql_close($connect);
}

if($titolo === '' && $numero === '' && $testi === '' && $disegni === '')
{
  echo $form;
}
else if($titolo != '' && $numero === '' && $testi === '' && $disegni === '' )
{
  echo $form;
  connect();
  search($titolo, null);
}
else if($titolo === '' && $numero != '' && $testi === '' && $disegni === '' )
{
  echo $form;
  connect();
  search($numero, null);
}
else if($titolo === '' && $numero === '' && $testi != '' && $disegni === '' )
{
  echo $form;
  connect();
  search($testi, null);
}
else if($titolo === '' && $numero === '' && $testi === '' && $disegni != '' )
{
  echo $form;
  connect();
  search($disegni, null);
}
else if($titolo === '' && $numero === '' && $testi != '' && $disegni != '' )
{
  echo $form;
  connect();
  search($testi, $disegni);
}
else
{
  echo $form;
  echo "<h1>ATTENZIONE! Selezionare un solo campo di ricerca per volta!</h1>";
}
?>
Grazie ancora.
 
Discussioni simili
Autore Titolo Forum Risposte Data
I Sto progettando nuovi siti utilizzando bootstrap e devo dire funziona bene, l'unico problema e la maschera -moz- HTML e CSS 0
K Problema form update PHP 2
O problema con dvr dahua xvr5116 IP Cam e Videosorveglianza 0
S Problema nel ciclare un json Javascript 0
G Problema con Xampp Web Server 1
andrea barletta Problema con miniature comandi Photoshop 0
I problema con alice Posta Elettronica 0
K Problema Inner join PHP 1
F firefox problema http Linux e Software 0
N Problema con position absolute e overflow HTML e CSS 4
E Problema jquery Success jQuery 2
L Problema con inner join PHP 11
K [php] Problema con inner join PHP 4
E problema selezione sfumata Photoshop 2
K [PHP] Problema con variabili concatenate. PHP 1
A Problema filtro fluidifica Photoshop Photoshop 1
H Problema Bordi Scontorno Photoshop 1
O problema con query PHP 4
R Problema installazione Realtek WiFi USB rtl8821 Reti LAN e Wireless 0
I problema con 2 account Posta Elettronica 1
L problema collegamento file css con html HTML e CSS 1
Y Problema percorso file in rete PHP 1
N Problema SEO "L'URL non si trova su Google" SEO e Posizionamento 4
E Problema accesso a file con app sviluppata con MIT APP INVENTOR 2 Sviluppo app per Android 0
P Problema acquisizione clienti Webdesign e Grafica 1
F NetBeans problema creazione progetto Java Windows e Software 0
M Problema con Try Catch PHP 0
C problema seo + cerco esperto SEO e Posizionamento 11
Sergio Unia Problema con gli eventi del mouse su una data table: Javascript 2
T PROBLEMA CON SESSIONI PHP 3
A Problema, non so, di scale() o transform, oppure altro? HTML e CSS 0
T ALTRO PROBLEMA CON ARRAY PHP PHP 1
R problema con else PHP 0
T PROBLEMA CON ARRAY PHP 8
L problema con query select PHP 2
R Problema query con ricerca id numerico PHP 2
F Problema con risposta PHP 0
S problema con recupero dati tabella mysql PHP 2
Z Problema con il mio tp-l i nk Reti LAN e Wireless 1
I PROBLEMA: Sostituzione sito XAMPP E-Commerce 0
T problema data 30/11/-1 PHP 0
L Problema RAM con Tomcat 8 Apache 0
napuleone problema con sort e asort PHP 4
Y Problema incolonnamento tabella PHP 7
S problema salvataggio immagini Photoshop 0
Z Problema con INT MySQL PHP 1
Z Problema database MySQL con XAMPP PHP 0
M Problema con controllo form in real time jQuery 6
D problema php mysql PHP 1
D problema php mysql PHP 1

Discussioni simili