PHP  
downloads | documentation | faq | getting help | mailing lists | | php.net sites | links | my php.net 
search for in the  
<com_setcall_user_method_array>
view the version of this page
Last updated: Tue, 22 Apr 2003

IX. Klasse/Object Functies

Introductie

Deze functies stellen je in staat informatie op te vragen over klassen en ge�nstantieerde objecten. Je kunt bijvoorbeeld de naam van een klasse waartoe een object behoort opvragen of alle eigenschappen en namen van methoden. Met deze functies kun je niet alleen de namen van de klasse opvragen maar ook hoe zijn familie (door overerving) er uit ziet (bijv. opvragen wat de ouder van een bepaald object is).

Voorbeelden

In dit voorbeeld defini�ren we een basis klasse en een uitbreiding daarop. De basis klasse Groente beschrijft een groente; of deze eetbaar is en wat zijn kleur is. De subklasse Spinazie voegt een methode toe om deze groente te koken en om er achter te komen of deze reeds gekookt is.

Voorbeeld 1. klassen.inc

<?php
/* Basis klasse met eigenschappen en methoden */
class Groente {

    var $eetbaar;
    var $kleur;

    function Groente( $eetbaar, $kleur="groen" ) {
        $this->eetbaar = $eetbaar;
        $this->kleur = $kleur;
    }

    function is_eetbaar() {
        return $this->eetbaar;
    }

    function welke_kleur() {
        return $this->kleur;
    }
    
} /* Einde van klasse Groente */

/* De klasse Spinazie breidt de basis klasse uit. */
class Spinazie extends Groente {

    var $gekookt = false;

    function Spinazie() {
        $this->Groente( true, "groen" );
    }

    function koken() {
        $this->gekookt = true;
    }

    function is_gekookt() {
        return $this->gekookt;
    }
    
} /* Einde van klasse Spinazie */

?>

Vervolgens instanti�ren we 2 objecten van deze klassen en geven wat informatie over hun weer, waaronder hun ouderschap. We defini�ren ook wat handige functies, maar deze dienen enkel om de informatie mooi weer te geven.

Voorbeeld 2. test_script.php

<pre>
<?php

include "klassen.inc";

/* Handige functies */ 

function print_vars($obj) {
    $eigenschappen = get_object_vars($obj);
    while (list($eigenschap, $waarde) = each($eigenschappen))
        echo "\t$eigenschap = $waarde\n";
}

function print_methoden($obj) {
    $methoden = get_class_methods(get_class($obj));
    foreach ($methoden as $methode_naam)
        echo "\tfunction $methode_naam()\n";
}

function klasse_ouderschap($obj, $klasse) {
    global $$obj;
    if (is_subklasse_of($$obj, $klasse)) {
        echo "Object $obj behoort toe klasse ".get_class($$obj);
        echo " een subklasse van $klasse\n";
    } else {
        echo "Object $obj behoort niet tot een subklasse van $klasse\n";
    }
}

// Maak 2 objecten

$groente = new Groente(true,"blauw");
$blaadje = new Spinazie();

// Geef informatie over de objecten weer.
echo "\$groente: KLASSE " . get_class($groente) . "\n";
echo "\$blaadje: KLASSE " . get_class($blaadje) . "\n";
echo ", OUDER " . get_parent_class($blaadje) . "\n";

// Geef eigenschappen van $groente weer 
echo "\n\$groente: Eigenschappen\n";
print_vars($groete);

// Geef de namen van de methoden van $groente weer 
echo "\nblaadje: Methoden\n";
print_methoden($blaadje);

echo "\nOuderschap:\n";
klasse_ouderschap('blaadje', 'Spinazie');
klasse_ouderschap('blaady', 'Groente');
?>
</pre>

Het is belangrijk om te onthouden dat in bovenstaand voorbeeld, het object $blaadje een instantie is van de klasse Spinazie welke een subklasse van Groente is. Daarom zal het script de volgende output geven:

[...]
Ouderschap:
Object $blaadje behoort niet tot een subklasse van Spinazie
Object $blaadje behoort tot klasse Spinazie een subkklasse van Groente

Inhoudsopgave
call_user_method_array --  Roept een door de programmeur gedefinieerde methode aan met een array van parameters [vervangen].
call_user_method --  Roept een methode aan op een door de programmeur gespecificeerd object [vervangen]
class_exists -- Controleert of de gegeven naam bestaat als klasse
get_class_methods -- Retourneert een array met de namen van methodes van een klasse
get_class_vars --  Retourneert een array met alle eigenschappen van een klasse.
get_class -- Retourneert de naam van de klasse waarvan het gegeven object ge�nstantieerd is.
get_declared_classes -- Retourneert een array met de namen van alle gedefinieerde klassen.
get_object_vars -- Retourneert een array met alle eigenschappen van een object
get_parent_class -- Retourneert de klasse naam van de ouder van het gegeven object of klasse naam.
is_a --  Retourneert TRUE als het gegeven object tot deze klasse behoort of als de klasse een van de ouders is.
is_subclass_of --  Retourneert TRUE als het object deze klasse als een van z'n ouders heeft.
method_exists -- Controleert of de gegeven methode in een klasse definitie voorkomt


User Contributed Notes
Klasse/Object Functies
add a note add a note
gateschris at yahoo dot com
08-Mar-2001 08: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.

kevin at gambitdesign dot com
04-Jun-2001 09: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

a2zofciv2 at hotmail dot com
29-Sep-2001 05: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 10:18
New to OOP?  This listing of beginner PHP OOP tutorials may help:
 

zzz at iz4u dot net
24-Feb-2002 07: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 04: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

ma++ at ender dot com
20-Mar-2002 05: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 01: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

matthew at fireflydigital dot com
29-Apr-2002 04: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();
}

justin at quadmyre dot com
19-Aug-2002 04: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);

?>

einhverfr at not-this-host dot hotmail dot com
14-Sep-2002 07:35

You may find it helpful in complex projects to have namespaces for your classes, and arrange these in a hierarchical manner.   A simple way to do this is to use the filesystem to order your hierarchies and then define a function like this:

function use_namespace($namespace){

require_once("namespaces/$namespace.obj.php");

}

(lack of indentation due to HTML UI for this page)
This requires that all your object libraries end in .obj.php (which I use) but you can modfy it to suit your needs.  To call it you could, for exmaple call:

use_namespace("example");
or if foo is part of example you can call:
use_namespace("example/foo");

asommer*at*as-media.com
20-Sep-2002 09:52

Something I found out just now that comes in very handy for my current project:

it is possible to have a class override itself in any method ( including the constructor ) like this:

class a {

..function ha ( ) {
....if ( $some_expr ) {
......$this = new b;
......return $this->ha ( );
....}
....return $something;
..}

}

in this case assuming that class b is already defined and also has the method ha ( )

note that the code after the statement to override itself is still executed but now applies to the new class

i did not find any information about this behaviour anywhere, so i have no clue wether this is supposed to be like this and if it might change... but it opens a few possibilities in flexible scripting!!

ernest at vogelsinger dot at
24-Oct-2002 02:18

It appears as if "include()" and "require()" cannot appear inside a class definition, but outside a class method.

For example, the construct
class A {
include ('class_a_methods.php');
}
returns an error (unexpected T_INCLUDE), but
class A {
function foo() {
include ('class_a_foo_method.php');
}
}
works as expected.

This is a slight annoyance if one wants to keep class code in manageable chunks.

alex at liniumNOSPAM dot net
13-Dec-2002 08:39

Using the good old eval() function, it is possible to dynamically create classes. I found this very useful because I could generate a class dynamically based on the structure of an XML document. For example:

$classString = 'class someClass { var $someVar = "someValue"; }';
eval($classString);
$someObject = new someClass;
echo $someObject->someVar;

This will print "someValue" as expected. This very simple example is pointless, as it would be easier to just create the class in the normal way, but here is where it gets interesting:

$varString = "";
for ($i = 1; $i <= 3; $i++) {
$varString .= "var \$var$i = $i; ";
}

$classString = "class someClass { $varString }";
eval($classString);

$someObject = new someClass;
echo $someObject->var1;
echo $someObject->var2;
echo $someObject->var3;

This prints 1 2 3. Cool huh?

Now it just so happens that its possible to declare classes within functions, so its actually possible to make a function that will create a class on the parameters you supply to it. Now try doing THAT in ASP!!!

info at free-dev dot com
15-Feb-2003 09:03

A constructor (a code with runs in the initialization of the class) can be used, like in the C language. Here's an example :

<?
class int {
function int() { echo "constructor"; }
}
$myint = new int; // creates a new instance and call the constructor
?>

The constructor's function name MUST be the same as the class name. If you want to pass arguments in the constructor, use this :

<?
class int {
function int($str) { echo $str; }
}
$myint = new int("hello");
?>

Now you can show hello at the initialization of the class. I tried to see if I could use the destructor (~classname) but it doesn't seems do work :-( it you want to use a variable in a class, you must create a new instance of it. Example :

<?
class i {
var $m=array("a", "b", "c");
function s() { echo $m[0]; }
}
i::s(); // it doesn't work because $m is set to nothing

$int = new i; // create instance and sets m
$int->s(); // now it shows the right value
?>

Carlos
05-Apr-2003 12:32

Commenting the above example:

We read: "$int->s(); // now it shows the right value". But no, it it won't, even if expected ;) The s() is buggy and should be:

function s() { echo $this->m[0]; }

then it will work. ;)

ninja (a : t) thinkninja (d : o : t) com
10-May-2003 06:37

the best way i found to call an instance of a class from within another class is like so:

class foo {
 
var $meta = 1;

}

class bar {

var $foo;

function bar(&$objref) //constructor
{
  $this->foo =& $objref;
}

function doohickey()
{
  return $this->foo->meta;
}

}

$fooclass = new foo();
$barclass = new bar($fooclass);

echo $barclass->doohickey();

add a note add a note

<com_setcall_user_method_array>
 Last updated: Tue, 22 Apr 2003
show source | credits | mirror sites 
Copyright © 2001-2003 The PHP Group
All rights reserved.
This mirror generously provided by: /
Last updated: Sun May 25 21:10:51 2003 CEST