PHP: Oszt�ly/Objektum f�ggv�nyek - Manual
PHP  
downloads | documentation | faq | getting help | mailing lists | | php.net sites | links 
search for in the  
previouscom_setcall_user_method_arraynext
Last updated: Fri, 30 Aug 2002
view the printer friendly version or the printer friendly version with notes or change language to English | Brazilian Portuguese | Chinese | Czech | Dutch | Finnish | French | German | Italian | Japanese | Korean | Polish | Romanian | Russian | Spanish | Swedish | Turkish

IX. Oszt�ly/Objektum f�ggv�nyek

Bevezet�s

A f�ggv�nyekr�l

Ezek a f�ggv�nyek PHP oszt�lyokr�l �s objektump�ld�nyokr�l adnak inform�ci�kat, mint p�ld�ul: az objektum oszt�ly�nak nev�t (t�pus�t), a tagv�ltoz�it m�sn�ven tulajdons�gait, �s met�dusait is. Ezekkel a f�ggv�nyekkel egy objektumnak nem csak az oszt�ly-tags�g�t lehet meg�llap�tani, hanem a sz�rmaz�s�t is, azaz, melyik oszt�lyt kiterjeszt�se az adott objektum oszt�ly.

Egy haszn�lati p�lda

Ebben a p�ld�ban defini�lunk egy alap oszt�lyt, �s ennek egy kiterjeszt�s�t. Az alap oszt�ly le�r egy z�lds�get (Zoldseg), meghat�rozva, hogy ehet�-e vagy sem (eheto), �s hogy milyen sz�n�. Az aloszt�ly a paraj (Paraj) hozz�ad egy �j met�dust, hogy megf�zhesd, �s egy m�sikat, hogy meg�llap�tsd, hogy f�tt-e.

P�lda 1. classes.inc

<?php
// alap oszt�ly tulajdons�gokkal �s met�dusokkal
class Zoldseg {

  var $eheto;
  var $szin;

  function Zoldseg ( $eheto, $szin="z�ld" ) {
    $this->eheto = $eheto;
    $this->szin = $szin;
  }

  function eheto_e() {
    return $this->eheto;
  }

  function milyen_szinu() {
    return $this->szin;
  }
  
} // v�ge a Zoldseg oszt�lynak

// kiterjesztj�k az alap oszt�lyt
class Paraj extends Zoldseg {

  var $megfozve = false;

  function Paraj() {
    $this->Zoldseg ( true, "z�ld" );
  }

  function fozes() {
    $this->megfozve = true;
  }

  function fott_e() {
    return $this->megfozve;
  }
  
} // v�ge a Paraj oszt�ynak

?>

Most k�t p�ld�nyt l�trehozunk a fenti oszt�lyokb�l, �s inform�ci�kat �runk ki r�lunk, bele�rtve az sz�rmaz�sukat is. Defini�lunk n�h�ny hasznos f�ggv�nyt, f�leg az�rt, hogy ezeket az inform�ci�kat sz�pen �rjuk ki.

P�lda 2. test_script.php

<pre>
<?php

include "classes.inc";

// hasznos f�ggv�nyek

function valtozok_kiirasa($obj) {
  $tomb = get_object_vars($obj);
  while (list($tul, $ertek) = each($tomb))
    echo "\t$tul = $ertek\n";
}

function metodusok_kiirasa($obj) {
  $tomb = get_class_methods(get_class($obj));
  foreach ($tomb as $metodus)
    echo "\tfunction $metodus()\n";
}

function os_osztaly($obj, $osztaly) {
  global $$obj;
  if (is_subclass_of($$obj, $osztaly)) {
    echo "A $obj a " . get_class($$obj) . " oszt�lyhoz tartozik, ";
    echo "ami a $class egy aloszt�lya.\n";
  } else {
    echo "A $obj nem tartozik $class egy aloszt�ly�hoz.\n";
  }
}

// k�t objektump�ld�ny l�trehoz�sa

$karalabe  = new Zoldseg(true,"k�k");
$soklevelu = new Paraj();

// objektuminform�ci�k ki�r�sa
echo "karalabe: CLASS " . get_class($karalabe) . "\n";
echo "soklevelu: CLASS " . get_class($soklevelu);
echo " PARENT " . get_parent_class($soklevelu) . "\n";

// a karal�b� tulajdons�gai
echo "\nkaralabe: Tulajdons�gok\n";
valtozok_kiirasa($karalabe);

// a soklevel� paraj met�dusai
echo "\nsoklevelu: Met�dusok\n";
metodusok_kiirasa($soklevelu);

echo "\nSz�l�k:\n";
os_osztaly("soklevelu", "Paraj");
os_osztaly("soklevelu", "Zoldseg");
?>
</pre>

Fontos �szrevenni, hogy a fenti p�ld�ban a $soklevelu a Paraj objektum egy p�ld�nya, amely a Zoldseg egy aloszt�lya objektumnak, ez�rt a programunk utols� r�sze a k�vetkez�t �rja ki (szerencs�re nincs probl�ma a n�vel�kkel :)

[...]
Sz�l�k:
A soklevelu nem tartozik Paraj egy aloszt�ly�hoz.
A soklevelu a paraj oszt�lyhoz tartozik, ami a Zoldseg egy aloszt�lya.

Tartalom
call_user_method_array --  megh�vja az adott objektum egy met�dus�t param�tert�mbbel [ellenjavallt]
call_user_method --  Egy megadott objektumon bel�l megh�v egy f�ggv�nyt [ellenjavallt]
class_exists -- megvizsg�lja, hogy defini�lt-e az oszt�ly
get_class_methods -- Oszt�lymet�dusnevek t�mbj�vel t�r vissza.
get_class_vars --  visszaadja az oszt�ly alaptulajdons�gait egy t�mbben
get_class -- visszaadja egy objektum oszt�ly�nak a nev�t
get_declared_classes -- visszaadja a jelenlegi szkriptben defini�lt oszt�lyok neveit
get_object_vars -- Objektumtulajdons�gok asszociat�v t�mbj�vel t�r vissza
get_parent_class -- visszaadja egy objektum vagy oszt�ly sz�l� oszt�ly�t
is_a --  megvizsg�lja, hogy az objektum lesz�rmazottja vagy tagja-e egy oszt�lynak
is_subclass_of --  megviszg�lja, hogy egy objektum egy megadott oszt�lynak egy aloszt�ly�hoz tartozik-e
method_exists -- ellen�rzi az oszt�lymet�dus l�tez�s�t
User Contributed Notes
Oszt�ly/Objektum f�ggv�nyek
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: Fri, 30 Aug 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