PHP  
downloads | documentation | faq | getting help | | php.net sites | links 
search for in the  
previouscom_setcall_user_methodnext
Last updated: Tue, 28 May 2002
view this page in Printer friendly version | English | Brazilian Portuguese | Czech | Dutch | French | German | Hungarian | Italian | Japanese | Korean | Polish | Romanian | Russian | Spanish | Turkish

IX. Class/Object Functions

Introduction

These functions allow you to obtain information about classes and instance objects. You can obtain the name of the class to which a object belongs, as well as its member properties and methods. Using these functions, you can find out not only the class membership of an object, but also its parentage (i.e. what class is the object class extending).

Examples

In this example, we first define a base class and an extension of the class. The base class describes a general vegetable, whether it is edible or not and what is its color. The subclass Spinach adds a method to cook it and another to find out if it is cooked.

Esimerkki 1. classes.inc

<?php

// base class with member properties and methods
class Vegetable {

    var $edible;
    var $color;

    function Vegetable( $edible, $color="green" ) {
        $this->edible = $edible;
        $this->color = $color;
    }

    function is_edible() {
        return $this->edible;
    }

    function what_color() {
        return $this->color;
    }
    
} // end of class Vegetable

// extends the base class
class Spinach extends Vegetable {

    var $cooked = false;

    function Spinach() {
        $this->Vegetable( true, "green" );
    }

    function cook_it() {
        $this->cooked = true;
    }

    function is_cooked() {
        return $this->cooked;
    }
    
} // end of class Spinach

?>

We then instantiate 2 objects from these classes and print out information about them, including their class parentage. We also define some utility functions, mainly to have a nice printout of the variables.

Esimerkki 2. test_script.php

<pre>
<?php

include "classes.inc";

// utility functions

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 "Object $obj belongs to class ".get_class($$obj);
        echo " a subclass of $class\n";
    } else {
        echo "Object $obj does not belong to a subclass of $class\n";
    }
}

// instantiate 2 objects

$veggie = new Vegetable(true,"blue");
$leafy = new Spinach();

// print out information about objects
echo "veggie: CLASS ".get_class($veggie)."\n";
echo "leafy: CLASS ".get_class($leafy);
echo ", PARENT ".get_parent_class($leafy)."\n";

// show veggie properties
echo "\nveggie: Properties\n";
print_vars($veggie);

// and leafy methods
echo "\nleafy: Methods\n";
print_methods($leafy);

echo "\nParentage:\n";
class_parentage("leafy", "Spinach");
class_parentage("leafy", "Vegetable");
?>
</pre>

One important thing to note in the example above is that the object $leafy is an instance of the class Spinach which is a subclass of Vegetable, therefore the last part of the script above will output:

[...]
Parentage:
Object leafy does not belong to a subclass of Spinach
Object leafy belongs to class spinach a subclass of Vegetable

Sis�llys
call_user_method --  Call a user method on an specific object [deprecated]
call_user_method_array --  Call a user method given with an array of parameters [deprecated]
class_exists -- Checks if the class has been defined
get_class -- Returns the name of the class of an object
get_class_methods -- Returns an array of class methods' names
get_class_vars --  Returns an array of default properties of the class
get_declared_classes -- Returns an array with the name of the defined classes
get_object_vars -- Returns an associative array of object properties
get_parent_class -- Retrieves the parent class name for object or class
is_a --  Returns true if the object is of this class or has this class as one of its parents
is_subclass_of --  Returns true if the object has this class as one of its parents
method_exists -- Checks if the class method exists
User Contributed Notes
Class/Object Functions
add a note about notes

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.


04-Jun-2001 08:27

i came across an errer 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


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:
  


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


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


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();
}

add a note about notes
previouscom_setcall_user_methodnext
Last updated: Tue, 28 May 2002
show source | credits | stats | mirror sites:  
Copyright © 2001, 2002 The PHP Group
All rights reserved.
This mirror generously provided by:
Last updated: Thu Jul 4 12:06:15 2002 CEST