|
|
 |
IX. Funzioni per Classi/Oggetti Introduzione
Queste funzioni permettono di ottenere informazioni sulle classi
e sulle istanze degli oggetti. Si può ricavare il nome della
classe da cui deriva un dato oggetto, come le sue proprietà e i
suoi metodi. Utilizzando queste funzioni si ottiene, non solo a
quale classe appartiene un dato oggetto, ma anche i suoi "padri"
(ad esempio da quale classe è derivata la classe dell'oggetto).
RequisitiNon sono necessarie librerie esterne per utilizzare questo modulo. InstallazioneNon è necessaria nessuna installazione per usare queste
funzioni, esse fanno parte del core di PHP. Configurazione di RuntimeQuesta estensione non definisce
alcuna direttiva di configurazione in php.ini Tipi di risorseQuesta estensione non definisce alcun tipo di risorsa. Costanti predefiniteQuesta estensione non definisce alcuna costante. Esempi
In questo esempio, prima si definisce una classe base, quindi una
seconda che deriva dalla prima. La classe base descrive gli aspetti
generali degli ortaggi, se è commestibile e quale sia il colore. La
classe derivata Spinaci aggiunge i metodi di
cottura e di verifica della completa cottura.
Esempio 1. classi.inc |
<?php
class Ortaggio {
var $commestibile;
var $colore;
function Ortaggio($commestibile, $colore="verde")
{
$this->commestibile = $commestibile;
$this->colore = $colore;
}
function e_commestibile()
{
return $this->commestibile;
}
function che_colore_ha()
{
return $this->colore;
}
} class Spinaci extends Ortaggio {
var $cotto = false;
function Spinaci()
{
$this->Ortaggio( true, "verde" );
}
function cuocilo()
{
$this->cotto = true;
}
function e_cotto()
{
return $this->cotto;
}
} ?>
|
|
A questo punto si istanziano 2 oggetti a partire da queste classi
e si visualizzeranno le informazioni relative a questi oggetti, compresi
i loro padri. Verranno anche inserite funzioni di utilità
principalmente con lo scopo di rendere chiara la visualizzazione delle
variabili.
Esempio 2. test_script.php |
<pre>
<?php
include "classi.inc";
function visualizza_var($oggetto)
{
$matrice = get_object_vars($oggetto);
while (list($prop, $val) = each($matrice))
echo "\t$prop = $val\n";
}
function visualizza_metodi($oggetto)
{
$matrice = get_class_methods(get_class($oggetto));
foreach ($matrice as $metodo)
echo "\tfunzione $metodo()\n";
}
function padri_classe($oggetto, $classe)
{
if (is_subclass_of($$oggetto, $classe)) {
echo "Oggetto $oggetto appartiene alla classe ".get_class($$oggetto);
echo " derivata da $classe\n";
} else {
echo "Oggetto $oggetto non deriva da una sottoclasse di $classe\n";
}
}
$pomodoro = new Ortaggio(true,"rosso");
$frondoso = new Spinaci();
echo "pomodoro: CLASSE " . get_class($pomodoro) . "\n";
echo "frondoso: CLASSE " . get_class($frondoso);
echo ", PADRE " . get_parent_class($frondoso) . "\n";
echo "\npomodoro: Proprietà\n";
visualizza_var($pomodoro);
echo "\nfrondoso: Metodi\n";
visualizza_metodi($frondoso);
echo "\nPadri:\n";
padri_classe("frondoso", "Spinaci");
padri_classe("frondoso", "Ortaggio");
?>
</pre>
|
Un aspetto da notare nell'esempio precedente è che l'oggetto
$frondoso è un'istanza della classe
Spinaci che a sua volta è una sottoclasse di
Ortaggio, quindi l'ultima parte dell'esempio
visualizzerà:
[...]
Padri:
Oggetto frondoso non deriva da una sottoclasse di Spinaci
Oggetto frondoso appartiene alla classe spinaci derivata da Ortaggio |
|
- Sommario
- call_user_method_array --
Richiama il metodo dato con un array di parametri [deprecated]
- call_user_method --
Chiama un metodo dell'oggetto indicato [deprecated]
- class_exists -- Verifica se una classe è stata definita
- get_class_methods -- Restituisce un array con i nomi dei metodi della classe
- get_class_vars --
Restituisce un array con le proprietà di default della classe
- get_class -- Restituisce il nome della classe di un oggetto
- get_declared_classes -- Restituisce un array con il nome delle classi definite
- get_declared_interfaces --
Returns an array of all declared interfaces.
- get_object_vars -- Restituisce un array associativo con le proprietà dell'oggetto
- get_parent_class -- Restituisce il nome della classe genitrice di un oggetto o di una classe
- is_a --
Restituisce TRUE se l'oggetto appartiene a questa classe o se ha
questa classe tra i suoi genitori
- is_subclass_of --
Restituisce TRUE se l'oggetto ha questa classe come uno dei suoi genitori
- method_exists -- Verifica se il metodo esiste nella classe
add a note
User Contributed Notes
Funzioni per Classi/Oggetti
mfirat at fibronline dot com
02-Apr-2004 12:18
<?php
class calculator {
var $c;
function addition($a, $b) {
$this->c = $a + $b;
return $this->c;
}
function subtraction($a, $b) {
$this->c = $a - $b;
return $this->c;
}
function multiplication($a, $b) {
$this->c = $a * $b;
return $this->c;
}
function division($a, $b) {
$this->c = $a / $b;
return $this->c;
}
}
$cc = new calculator;
echo $cc->addition(20, 10)."<br>";
echo $cc->subtraction(20, 10)."<br>";
echo $cc->multiplication(20, 10)."<br>";
echo $cc->division(20, 10)."<br>";
?>
Fasoro Oladipo <dipofasoro at yahoo dot co dot uk>
14-Mar-2004 03:49
<?php
class user {
var $dbconn
function user() {
$this->dbconn = DB::getInformix();
}
function Login($uname, $pass) {
}
function Register($uname, $pass, $name, $email) {
}
function FeedBack($name, $email, $msg) {
}
function Update($name, $email) {
}
function UnRegister() {
}
}
class template {
function showlogin() {
}
function showwelcome() {
}
}
class DB {
function getInformix() {
}
function getMySQL() {
}
function getPostGRESQL() {
}
}
$usr = new user();
$usr->Login($_POST["uname"], $_POST["pass"]);
$usr->Register($_POST["uname"], $_POST["pass"], $_POST["name"], $_POST["email"]);
Login($uname, $pass, $rememberIP);
$usr->Login($_POST["uname"], $_POST["pass"], isset($_POST["remeberIP"]);
?>
heleon
12-Jan-2004 08:22
Hi again,
...to get around the undeclared properties problem is to use Get/Set-functions. The way it should be, and has to be in PHP to be secure.
Heleon
heleon@ergens
12-Jan-2004 08:11
Hi,
Take care with setting properties outside a class. I thought I had extended a var named Name en used it outside its class. After some searching I found that it was not the extended Name that was set but a new generated one. Created when setting it. With normal variables I don't find undeclared vars a problem. But with classes it could get messy I think.
$this->Characters[$this->CharacterID]->Name = "Hank";
Heleon
ar at 5mm de
28-Aug-2003 01:59
I missed some kind of function to dynamicly override or extend an Object:
-----------------------------------------
function &extendObj(&$obj, $code) {
static $num = 0;
$classname = get_class($obj);
$newclass = $classname.$num;
eval('class '.$newclass.' extends '.$classname.' { '.$code.' }');
$newobj = new $newclass();
$vars = get_class_vars($classname);
foreach($vars AS $key=>$value) {
$newobj->$key = &$obj->$key;
}
return $newobj;
}
-----------------------------------------
This creates a new class which extends the old one by the given code parameter, instanciates it and copy all vars from the old obj to the new one.
-----------------------------------------
class testA {
var $prop = 'a';
function funcA($val) {
$this->prop = $val;
}
function value() {
return $this->prop;
}
}
$obj = new testA();
$newobj = &extendObj(&$obj, 'function addX() { $this->prop .= "x"; }');
$newobj->funcA('abc');
$newobj->addX();
echo $newobj->value();
-----------------------------------------
Results in 'abcx'. You can use the function multiple times and also with class variables. Be carefull, even if $newobj is just a copy of $obj, $obj->value() will return 'abcx', too, because of the & operator: $newobj->$key = &$obj->$key;
pixellent at stodge dot net
19-Aug-2003 05:07
In case you were wondering, you can't do the following in PHP:
$name = wsConfig::GetInstance()->GetValue("name");
It causes a parse error, I think due to trying to call GetValue. And yes I do have a function called GetValue in my wsConfig class.
This is my singleton:
function &GetInstance()
{
static $Instance;
if (!isset($Instance))
{
$Instance = new wsConfig();
}
return $Instance;
}
zidsu at hotmail dot com
08-Jul-2003 11:24
FYI: if you want to split your class into manageble chunks, what means different files for you, you can put you functoins into includes, and make include() have a return value. Like this:
class Some_class {
var $value = 3;
function add_value ($input_param) {
return include ("path/some_file.php");
}
}
And your included file:
$input_param += $this->value;
return $input_param;
Then your function call will be:
$instance = new Some_class ();
$instance->add_value (3);
And this will return
6
hopefully :P
Keep in mind though, that the scope in the included file will be identical to the scope the function 'add_value' has.
And if you want to return the outcome, you should also have a return statement made in your include as well.
ninja (a : t) thinkninja (d : o : t) com
10-May-2003 05: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();
asommer*at*as-media.com
20-Sep-2002 08: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!!
einhverfr at not-this-host dot hotmail dot com
14-Sep-2002 06: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");
justin at quadmyre dot com
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=''; function class1(&$ref){ $this->ref_to_class=$ref; }
function test2($var){
$val = $this->ref_to_class->test($var); return $val;
}
}
$obj1=new class1;
$obj2=new class2($obj1);
$var=5;
$result=obj2->test2($var);
echo ($result);
?>
matthew at fireflydigital dot com
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("\"", """, 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();
}
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
a2zofciv2 at hotmail dot com
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
kevin at gambitdesign dot com
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
gateschris at yahoo dot com
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.
| |