learen more with autoformation

jeudi 9 octobre 2014

Utilisation des classes et des objets

Notre classe est maintenant prêt mais aucune utilisation tout seul. Comme nous l'avons expliqué ci-dessus, une classe est considéré comme un moule capable d'effectuer autant d'objets de même type et la même structure que celle désirée. Nous présentons maintenant la phase de réalisation d'une classe.

Instanciation d'une classe

L'instanciation d'une classe est la phase de création des objets issus de cette classe. Lorsque l'on instancie une classe, on utilise le mot-clé new suivant du nom de la classe. Cette instruction appelle la méthode constructeur ( __construct() ) qui construit l'objet et le place en mémoire. Voici un exemple qui illustre 4 instances différentes de la classes Personne.
Un objet est en fait une variable dont le type est la classe qui est instanciée. 
Création d'objets de type Personne
<?php
$personne1 = new Personne();
$personne2 = new Personne();
$personne3 = new Personne();
$personne4 = new Personne();
Remarque: Si nous avons défini les paramètres dans le constructeur de notre méthode de classe, nous devrions les avoir dans les parenthèses indiquent la durée de la procédure. Par exemple: $ person1 = new Personne ("Hamon», «Hugo»);

Accès aux attributs

Accès en écriture
Nous avons créé quatre objets de même type et la même structure. En l'état actuel, ils sont des clones parce que leurs attributs sont déclarés mais non initialisées. Nous attribuons à chacune de ces valeurs aux attributs de chaque objet.
Utilisation des attributs d'un objet
<?php
// Définition des attributs de la personne 1
$personne1->nom = 'Hamon';
$personne1->prenom = 'Hugo';
$personne1->dateDeNaissance = '02-07-1987';
$personne1->taille = '180';
$personne1->sexe = 'M';
// Définition des attributs de la personne 2
$personne2->nom = 'Dubois';
$personne2->prenom = 'Michelle';
$personne2->dateDeNaissance = '18-11-1968';
$personne2->taille = '166';
$personne2->sexe = 'F';
// Définition des attributs de la personne 3
$personne3->nom = 'Durand';
$personne3->prenom = 'Béatrice';
$personne3->dateDeNaissance = '02-08-1975';
$personne3->taille = '160';
$personne3->sexe = 'F';
// Définition des attributs de la personne 4
$personne4->nom = 'Martin';
$personne4->prenom = 'Pierre';
$personne4->dateDeNaissance = '23-05-1993';
$personne4->taille = '155';
$personne4->sexe = 'M';
Nous avons maintenant des objets ayant chacun des caractèristiques différentes.
Dans notre exemple, nous accèdons directement à la valeur de l'attribut. Cela est possible car nous avons défini l'attribut comme étant public. Si nous avions déclaré l'attribut avec les mots-clés private ouprotected, nous aurions du utiliser un autre mécanisme pour accéder à sa valeur ou bien la mettre à jour. Nous verrons cela dans un prochain cours.
Accès en lecture
La lecture de la valeur d'un attribut d'un objet se fait exactement de la même manière que pour une variable traditionnel. Le code suivant montre comment afficher le nom complet de la personne 1.
Affichage du nom et du prénom de la personne 1
<?php
echo 'Personne 1 :<br/><br/>';
echo 'Nom : ', $personne1->nom ,'<br/>';
echo 'Prénom : ', $personne1->prenom;
L'exécution de ce programme produit le résultat suivant sur la sortie standard :
Résultat d'exécution du code
Personne 1 :
Nom : Hamon
Prénom : Hugo
On 04:25 by مشاهير العرب in , ,    No comments
Nous avons défini le langage spécifique de programmation orientée objet. Vous entrez maintenant dans le vif du sujet, à savoir la déclaration et instanciation d'une classe. Nous allons déclarer une classe Person qui sera ensuite nous permettre de créer autant d'instances (objets) de cette classe que nous voulons.

                          Syntaxe de déclaration d'une classe

Le code suivant montre une manière de déclarer et de structurer convenablement une classe. Nous vous conseillons fortement de suivre ces conventions d'écriture
.<?php
class NomDeMaClasse
{
// Attributs
// Constantes
// Méthodes
}
?>
 <?phpclass Personne
{
// Attributs
public $nom;
public $prenom;
public $dateDeNaissance;
public $taille;
public $sexe;
// Constantes
const NOMBRE_DE_BRAS = 2;
const NOMBRE_DE_JAMBES = 2;
const NOMBRE_DE_YEUX = 2;
const NOMBRE_DE_PIEDS = 2;
const NOMBRE_DE_MAINS = 2;
// Méthodes
public function __construct() { }
public function boire()
{
echo 'La personne boit<br/>';
}
public function manger()
{
echo 'La personne mange<br/>';
}
}

mardi 7 octobre 2014

On 16:46 by مشاهير العرب in    No comments
conexion-php5Classe connexion de gestion simplifiée de MySQL en PHP5. Cette classe a sa propre gestion des erreurs. Il revient exceptions MySQLException genre.

Portion de code
<?php
  /**
  * Gestion des erreurs avec les exeptions
  */
  class MySQLExeption  extends Exception
  {
    public function __construct($Msg) {
      parent :: __construct($Msg);
    }
    public function RetourneErreur() {
      $msg  = '<div><strong>' . $this->getMessage() . '</strong>';
      $msg .= ' Ligne : ' . $this->getLine() . '</div>';
      return $msg;
    }
  }
?>
<?php
  class Mysql
  {
    private
      $Serveur     = '',
      $Bdd         = '',
      $Identifiant = '',
      $Mdp         = '',
      $Lien        = '',
      $Debogue     = true,
      $NbRequetes  = 0;
    /**
    * Constructeur de la classe
    * Connexion aux serveur de base de donnée et sélection de la base
    *
    * $Serveur     = L'hôte (ordinateur sur lequel Mysql est installé)
    * $Bdd         = Le nom de la base de données
    * $Identifiant = Le nom d'utilisateur
    * $Mdp         = Le mot de passe
    */
    public function __construct($Serveur = 'localhost', $Bdd = 'base', $Identifiant = 'root', $Mdp = '')
    {
      $this->Serveur     = $Serveur;
      $this->Bdd         = $Bdd;
      $this->Identifiant = $Identifiant;
      $this->Mdp         = $Mdp;
      $this->Lien=mysql_connect($this->Serveur, $this->Identifiant, $this->Mdp);
      if(!$this->Lien && $this->Debogue)
        throw new MySQLExeption('Erreur de connexion au serveur MySql!!!');
      $Base = mysql_select_db($this->Bdd,$this->Lien);
      if (!$Base && $this->Debogue)
        throw new MySQLExeption('Erreur de connexion à la base de donnees!!!');
    }
    /**
    * Retourne le nombre de requêtes SQL effectué par l'objet
    */
    public function RetourneNbRequetes()
    {
      return $this->NbRequetes;
    }
    /**
    * Envoie une requête SQL et récupère le résultât dans un tableau pré formaté
    *
    * $Requete = Requête SQL
    */
    public function TabResSQL($Requete)
    {
      $i = 0;
      $Ressource = mysql_query($Requete,$this->Lien);
      $TabResultat=array();
      if (!$Ressource and $this->Debogue) throw new MySQLExeption('Erreur de requête SQL!!!');
      while ($Ligne = mysql_fetch_assoc($Ressource))
      {
        foreach ($Ligne as $clef => $valeur) $TabResultat[$i][$clef] = $valeur;
        $i++;
      }
      mysql_free_result($Ressource);
      $this->NbRequetes++;
      return $TabResultat;
    }
    /**
    * Retourne le dernier identifiant généré par un champ de type AUTO_INCREMENT
    *
    */
    public function DernierId()
    {
        return mysql_insert_id($this->Lien);
    }
    /**
    * Envoie une requête SQL et retourne le nombre de table affecté
    *
    * $Requete = Requête SQL
    */
    public function ExecuteSQL($Requete)
    {
      $Ressource = mysql_query($Requete,$this->Lien);
      if (!$Ressource and $this->Debogue) throw new MySQLExeption('Erreur de requête SQL!!!');
      $this->NbRequetes++;
      $NbAffectee = mysql_affected_rows();
      return $NbAffectee;
    }
  }
?>
<?php
  /**
  * Utilisation de la classe
  */
  try
  {
    $Mysql = new Mysql('localhost', 'base', 'login', 'password');
    $Resulats = $Mysql->TabResSQL('SELECT Champ1,Champ2 FROM table');
    foreach ($Resulats as $Valeur)
    {
      echo $Valeur['Champ1'];
      echo $Valeur['Champ2'];
    }
  }
  catch (MySQLExeption $e)
  {
    echo $e -> RetourneErreur();
  }
?>
On 16:36 by مشاهير العرب   No comments
Trait Example From ZF2

namespace Zend\EventManager;
trait ProvidesEvents
{
public function setEventManager(EventManagerInterface $events)
{
$identifiers = array(__CLASS__, get_called_class());
$events->setIdentifiers($identifiers);
$this->events = $events;
return $this;
}
public function getEventManager()
{
if (!$this->events instanceof EventManagerInterface) {
$this->setEventManager(new EventManager());
}
return $this->events;
}
}

lundi 25 août 2014

php5.4 After the introduction to classes in the previous chapter, we're now ready to write our very own class. It will hold information about a generic user, for instance a user of your website. 

A class definition in PHP looks pretty much like a function declaration, but instead of using the function keyword, the class keyword is used. Let's start with a stub for our User class:
<?php
class User
{
    
}
?>
This is as simple as it gets, and as you can probably imagine, this class can do absolutely nothing at this point. We can still instantiate it though, which is done using the new keyword: 

$user = new User(); 

But since the class can't do anything yet, the $user object is just as useless. Let's remedy that by adding a couple of class variables and a method:
class User
{
    public $name;
    public $age;
    
    public function Describe()
    {
        return $this->name . " is " . $this->age . " years old";
    }
}
Okay, there are a couple of new concepts here. First of all, we declare two class variables, a name and an age. The variable name is prefixed by the access modifier "public", which basically means that the variable can be accessed from outside the class. We will have much more about access modifiers in one of the next chapters. 

Next, we define the Describe() function. As you can see, it looks just like a regular function declaration, but with a couple of exceptions. It has the public keyword in front of it, to specify the access modifier. Inside the function, we use the "$this" variable, to access the variables of the class it self. $this is a special variable in PHP, which is available within class functions and always refers to the object from which it is used. 

Now, let's try using our new class. The following code should go after the class has been declared or included:
$user = new User();
$user->name = "John Doe";
$user->age = 42;
echo $user->Describe();
The first thing you should notice is the use of the -> operator. We used it in the Describe() method as well, and it simply denotes that we wish to access something from the object used before the operator. $user->name is the same as saying "Give me the name variable on the $user object". After that, it's just like assigning a value to a normal variable, which we do twice, for the name and the age of the user object. In the last line, we call the Describe() method on the user object, which will return a string of information, which we then echo out. The result should look something like this: 


Congratulations, you have just defined and used your first class, but there is much more to classes than this. In the following chapters, we will have a look at all the possibilities of PHP classes.
On 04:33 by مشاهير العرب in , , , , , , ,    No comments
class-oopWhile classes and the entire concept of Object Oriented Programming (OOP) is the basis of lots of modern programming languages, PHP was built on the principles of functions instead. Basic support for classes was first introduced in version 4 of PHP but then re-written for version 5, for a more complete OOP support. Today, PHP is definitely usable for working with classes, and while the PHP library still mainly consists of functions, classes are now being added for various purposes. However, the main purpose is of course to write and use your own classes, which is what we will look into during the next chapters. 

Classes can be considered as a collection of methods, variables and constants. They often reflect a real-world thing, like a Car class or a Fruit class. You declare a class only once, but you can instantiate as many versions of it as can be contained in memory. An instance of a class is usually referred to as an object. 

If you're still a bit confused about what classes are and why you need them, don't worry. In the next chapter, we will write our very first class and use it. Hopefully that will give you a better idea of the entire concept.

samedi 23 août 2014

On 06:42 by مشاهير العرب in , , , , , , ,    No comments

What Is PHP?
PHP is an open-source, server-side, HTML-embedded Web-scripting language that is compati- ble with all the major Web servers (most notably Apache). PHP enables you to embed code fragments in normal HTML pages—code that is interpreted as your pages are served up to users. PHP also serves as a “glue” language, making it easy to connect your Web pages to server-side databases.
Why PHP ?
We devote nearly all of Chapter 1 to this question. The short answer is that it’s free, it’s open
source, it’s full featured, it’s cross-platform, it’s stable, it’s fast, it’s clearly designed, it’s easy
to learn, and it plays well with others.
What’s New in This Edition?
Although this book has a new title, it is in some sense a third edition. Previous versions were:
✦ PHP 4 Bible. Published in August 2000, covering PHP through version 4.0.
✦ PHP Bible, Second Edition. Published in September 2002, a significantly expanded ver-
sion of the first edition, current through PHP 4.2.
Our initial plan for this book was to simply reorganize the second edition and bring it up
to date with PHP5. We realized, however, that although the previous editions covered
PHP/MySQL interaction, we had left readers in the dark about how to create and administer
MySQL databases in the first place, and this led to many reader questions. As a result, we
decided to beef up the coverage of MySQL and change the title.
New PHP5 features
Although much of PHP4’s functionality survives unchanged in PHP5, there have been some
deep changes. Among the ones we cover are:
✦ Zend Engine 2 and the new object model, with support for private/protected members,
abstract classes, and interfaces

✦ PHP5’s completely reworked XML support, built around libmxl2

✦ Exceptions and exception handling

MySQL coverage
We now cover MySQL 4.0 installation, database design, and administration, including back-
ups, replication, and recovery. As with previous editions, we devote much of the book to
techniques for writing MySQL-backed PHP applications.
Other new material
In addition to MySQL- and PHP5-specific features, we’ve added:
✦ Improved coverage of databases other than MySQL (Oracle, PostgreSQL, and the PEAR
database interaction layer)

✦ The PEAR code repository

✦ A chapter on integrating PHP and Java

✦ Separate chapters on error-handling and debugging techniques

Finally, we reorganized the entire book, pushing more advanced topics toward the end, to
give beginners an easier ramp up.
Who wrote the book?
The first two editions were by Converse and Park, with a guest chapter by Dustin Mitchell
and tech editing by Richard Lynch. For this version, Clark Morgan took on much of the revi-
sion work, with help by Converse and Park as well as by David Wall and Chris Cornell, who
also contributed chapters and did technical editing.
Whom This Book Is For
This book is for anyone who wants to build Web sites that exhibit more complex behavior
than is possible with static HTML pages. Within that population, we had the following three
php_php5
particular audiences in mind:

✦ Web site designers who know HTML and want to move into creating dynamic Web sites
✦ Experienced programmers (in C, Java, Perl, and so on) without Web experience who
want to quickly get up to speed in server-side Web programming
✦ Web programmers who have used other server-side technologies (Active Server Pages,
Java Server Pages, or ColdFusion, for example) and want to upgrade or simply add
another tool to their kit. We assume that the reader is familiar with HTML and has a basic knowledge of the workings of the Web, but we do not assume any programming experience beyond that. To help save time for more experienced programmers, we include a number of notes and asides that com- pare PHP with other languages and indicate which chapters and sections may be safely skipped. Finally, see our appendixes, which offer specific advice for C programmers, ASP coders, and pure-HTML designers.