PHP  
downloads | documentation | faq | getting help | mailing lists | | php.net sites | links 
search for in the  
previouscom_setcall_user_method_arraynext
Last updated: Tue, 09 Jul 2002
view the printer friendly version or the printer friendly version with notes or change language to English | Brazilian Portuguese | Chinese | Czech | Dutch | Finnish | German | Hungarian | Italian | Japanese | Korean | Polish | Romanian | Russian | Spanish | Swedish | Turkish

IX. Objets

Introduction

About

Ces fonctions permettent de g�rer les classes et les objets. Vous pouvez notamment conna�tre le nom de la classe d'un objet, ses membres et ses m�thodes, et tous les objets parents (les classes qui sont �tendues par la classe d'un objet).

Exemple d'utilisation

Dans cet exemple, on d�finit une classe de base, et une extension. La classe de base d�finit un l�gume, s'il est mangeable ou pas, et sa couleur. La sous-classe epinard ajoute une m�thode pour le cuisiner, et une autre pour savoir s'il est cuisin�.

Exemple 1. classes.inc

<?php
// classe de base, avec ses membres et ses m�thodes
class Legume {
    var $mangeable;
    var $couleur;
    function legume( $mangeable, $couleur="green" ) {
        $this->mangeable = $mangeable;
        $this->couleur = $couleur;
    }
    function est_mangeable() {
        return $this->mangeable;
    }
    function quelle_couleur() {
        return $this->couleur;
    }
} // fin de la classe Legume
// extend la classe de base
class Epinard extends Legume {
    var $cuit = FALSE;
    function Epinard() {
        $this->Legume( TRUE, "green" );
    }
    function cuisine() {
        $this->cuit = TRUE;
    }
    function est_cuit() {
        return $this->cuit;
    }
} // fin de la classe Epinard
?>

Lorsqu'on instantie deux objets de ces classes, et qu'on affiche leurs informations, on affiche aussi leur h�ritage. On d�finit ici des utilitaires qui servent essentiellement � afficher ces informations proprement.

Exemple 2. test_script.php

<pre>
<?php
  include "classes.inc";
// utilitaires
  function print_vars($obj) {
    $arr = get_object_vars($obj);
    while (list($prop, $val) = each($arr))
        echo "\t$prop = $val\n";
  }
  function print_methods($obj) {
    $arr = get_class_methods(get_class($obj));
    foreach ($arr as $method)
        echo "\tfunction $method()\n";
  }
  function class_parentage($obj, $class) {
    global $$obj;
    if (is_subclass_of($$obj, $class)) {
        echo "L'objet $obj belongs to class ".get_class($$obj);
        echo " est une sous-classe de $class\n";
    } else {
        echo "L'objet $obj n'est pas une sous classe $class\n";
    }
  }
// instantie 2 objets
  $legume = new Legume(TRUE,"blue");
  $feuilles = new Epinard();
// affiche les informations sur ces objets
  echo "legume: CLASS ".get_class($legume)."\n";
  echo "feuilles: CLASS ".get_class($feuilles);
  echo ", PARENT ".get_parent_class($feuilles)."\n";
// affiche les propri�t�s du l�gume
  echo "\nl�gume: Propri�t�s \n";
  print_vars($legume);
// et les m�thodes de "feuilles"
  echo "\nfeuilles: Methods\n";
  print_methods($feuilles);
  echo "\nParent�e:\n";
  class_parentage("feuilles", "Epinard");
  class_parentage("feuilles", "Legume");
?>
</pre>

Il est important de noter que dans les exemples ci-dessus, les objets $feuilles sont une instance de Epinard qui est une sous-classe de Legume, donc la derni�re partie du script va afficher :

[...]
    Parent�e:
    L'objet feuilles n'est pas une sous classe Spinach
    L'objet feuilles est une sous-classe de Legume

Table des mati�res
call_user_method_array --  Appelle une m�thode utilisateur avec un tableau de param�tres
call_user_method --  Appelle une m�thode utilisateur d'un objet
class_exists -- V�rifie qu'une classe a �t� d�finie
get_class_methods -- Retourne les noms des m�thodes d'une classe.
get_class_vars --  Retourne les valeurs par d�faut des attributs d'une classe.
get_class -- Retourne la classe d'un objet
get_declared_classes -- Liste toutes les classes d�finies
get_object_vars --  Retourne un tableau associatif des propri�t�s d'un objet
get_parent_class -- Retourne le nom de la classe d'un objet
is_a --  Returns TRUE if the object is of this class or has this class as one of its parents
is_subclass_of --  D�termine si un objet est une sous-classe
method_exists --  V�rifie que la m�thode existe pour une classe.
User Contributed Notes
Objets
add a note about notes
[email protected]
08-Mar-2001 07:59

[Editor's note: If you are trying to do overriding, then you can just interrogate (perhaps in the method itself) about what class (get_class()) the object belongs to, or if it is a subclass of a particular root class.

You can alway refer to the parent overriden method, see the "Classes and Objects" page of the manual and comments/editor's notes therein.]

There is no function to determine if a member belongs to a base class or current class eg:

class foo {
function foo () { }
function a () { }
}

class bar extends foo {
function bar () { }
function a () { }
}

lala = new Bar();
------------------
how do we find programmatically if member a now belongs to class Bar or Foo.

[email protected]
04-Jun-2001 08:27

i came across an error something to the extent:

Fatal error: The script tried to execute a method or access a property of an incomplete object.

This was because I had included the file defining the class when i created the object but not in the script when i was trying to access the object as a member variable of a different object

[email protected]
29-Sep-2001 04:10

I spent 20 minutes or so trying to figure this out, maybe someone else has the same problem.

To access a class' function from within the class you would have to say $this->functionname(params), rather than just functionname(params) like in other programming languages.

Hope this helps

22-Nov-2001 09:18
New to OOP? This listing of beginner PHP OOP tutorials may help:

[email protected]
24-Feb-2002 06:34

array in class ^^

class CConfig
{
var $color = array(
'top' => "",
'write' => "",
'reply' => "",
'bottom1' => "",
'bottom2' => "",
'bottom3' => ""
);
}

don't do var color['write'];

saryon_no_spam_@unfix dot o r g
05-Mar-2002 03:46

Something nice i found out when i was trying to do with classes what i knew could be done with
functions: they can be dynamically loaded/used.

ex:

class a
{
function bla()
{
echo "1\n";
}
}

class b
{
function bla()
{
echo "2\n";
}
}

$class = "a";

$test = new $class;
$test->bla();

$class2 = "a";

$test2 = new $class2;
$test2->bla();

-----------------------

This will print:

1
2

------------------

For those of you who were considering doing something with plugins....use this to your
advantage :)

makes life soooo easy, this :)

Sar

[email protected]
20-Mar-2002 04:39

Actually, that example prints "1" and then "1", rather than "1" and then "2". I'm assuming the typo is that it should read $class2 = "b" instead of a.
c.bolten AT grafiknews DOT de
22-Apr-2002 12:14

another way to dynamically load your classes:

==========================
function loadlib($libname) {
$filename = "inc/".$libname.".inc.php";
// check if file exists...
if (file_exists($filename)) {
// load library
require($filename);
return TRUE;
}
else {
// print error!
die ("Could not load library $libname.\n");
}
}

:)

have phun!

-cornelius

[email protected]
29-Apr-2002 03:48

This is a pretty basic data structure, I know, but I come from a C++ background where these things were "da bomb" when I was first learning to implement them. Below is a class implementation for a queue (first-in-first-out) data structure that I used in a recent project at my workplace. I believe it should work for any type of data that's passed to it, as I used mySQL result objects and was able to pass the object from one page to another as a form element.

# queue.php

# Define the queue class
class queue
{
# Initialize class variables
var $queueData = array();
var $currentItem = 0;
var $lastItem = 0;

# This function adds an item to the end of the queue
function enqueue($object)
{
# Increment the last item counter
$this->lastItem = count($this->queueData);

# Add the item to the end of the queue
$this->queueData[$this->lastItem] = $object;
}

# This function removes an item from the front of the queue
function dequeue()
{
# If the queue is not empty...
if(! $this->is_empty())
{
# Get the object at the front of the queue
$object = $this->queueData[$this->currentItem];

# Remove the object at the front of the queue
unset($this->queueData[$this->currentItem]);

# Increment the current item counter
$this->currentItem++;

# Return the object
return $object;
}
# If the queue is empty...
else
{
# Return a null value
return null;
}
}

# This function specifies whether or not the queue is empty
function is_empty()
{
# If the queue is empty...
if($this->currentItem > $this->lastItem)

# Return a value of true
return true;

# If the queue is not empty...
else

# Return a value of false
return false;
}
}

?>

# Examples of the use of the class

# Make sure to include the file defining the class
include("queue.php");

# Create a new instance of the queue object
$q = new queue;

# Get data from a mySQL table
$query = "SELECT * FROM " . TABLE_NAME;
$result = mysql_query($query);

# For each row in the resulting recordset...
while($row = mysql_fetch_object($result))
{
# Enqueue the row
$q->enqueue($row);
}

# Convert the queue object to a byte stream for data transport
$queueData = ereg_replace("\"", "&quot;", serialize($q));

# Convert the queue from a byte stream back to an object
$q = unserialize(stripslashes($queueData));

# For each item in the queue...
while(! $q->is_empty())
{
# Dequeue an item from the queue
$row = $q->dequeue();
}

[email protected]
19-Aug-2002 03:38

If you want to be able to call an instance of a class from within another class, all you need to do is store a reference to the external class as a property of the local class (can use the constructor to pass this to the class), then call the external method like this:

$this->classref->memberfunction($vars);

or if the double '->' is too freaky for you, how about:

$ref=&$this->classref;
$ref->memberfunction($vars);

This is handy if you write something like a general SQL class that you want member functions in other classes to be able to use, but want to keep namespaces separate. Hope that helps someone.

Justin

Example:

<?php

class class1 {
function test($var) {
$result = $var + 2;
return $result;
}
}

class class2{
var $ref_to_class=''; # to be pointer to other class

function class1(&$ref){ #constructor
$this->ref_to_class=$ref; #save ref to other class as property of this class
}

function test2($var){
$val = $this->ref_to_class->test($var); #call other class using ref
return $val;
}
}

$obj1=new class1;
# obj1 is instantiated.
$obj2=new class2($obj1);
# pass ref to obj1 when instantiating obj2

$var=5;
$result=obj2->test2($var);
# call method in obj2, which calls method in obj1
echo ($result);

?>

add a note about notes
previouscom_setcall_user_method_arraynext
Last updated: Tue, 09 Jul 2002
show source | credits | stats | mirror sites
Copyright © 2001, 2002 The PHP Group
All rights reserved.
This mirror generously provided by:
Last updated: Sat Aug 31 06:19:44 2002 CEST