|
użytkowników online: 51
|
OPINIE UŻYTKOWNIKÓW
|
Prawdziwa skarbnica wiedzy na temat tworzenia stron WWW i nie tylko. Korzystam z porad praktycznie codziennie, jest mi to niezbędne w mojej pracy. Sam zajmuję się tworzeniem serwisów, ale porady pisane przez Darka sa dla mnie nieocenioną pomocą! Proste, czytelne i zrozumiałe dla każdego! Czekam na więcej!
Krzysztof Szypulski
KESS - projektowanie stron
|
|
PODRĘCZNIK PHP 5.x, 4.x, 3.x - częściowo spolszczony / źródło: www.php.net
[Spis]
[A]
[B]
[C]
[D]
[E]
[F]
[G]
[H]
[I]
[J]
[K]
[L]
[M]
[N]
[O]
[P]
[Q]
[R]
[S]
[T]
[U]
[V]
[X]
[W]
[Z]
XCII. Przeciążanie właściwości obiektów i wołania ich metod
Celem tego rozszerzenia jest umożliwienie przeciążania dostępu do
właściwości obiektów oraz wołania metod. Rozszerzenie to definiuje tylko
jedną funkcję, overload(), która przyjmuje jako
parametr nazwę klasy dla której przeciążanie powinno być udostępnione.
Klasa ta powinna mieć zdefiniowane odpowiednie metody, jeżeli chce
korzystać z tej dodatkowej funkcjonalności: __get(),
__set() oraz __call() odpowwiednio
dla pobierania/ustawiania wartości właściwości, lub wołania metod. Tym
sposobem przeciążanie może być dostępne wybiórczo. Wewnątrz tych funkcji
bsługujących przeciążanie, ono samo jest niedostępne by mieć możliwość
normalnego dostępu do właściwości obiektu.
| Ostrzeżenie | Ten moduł jest w stadium
EKSPERYMENTALNYM. Oznacza to, że zachowanie tych funkcji,
ich nazwy, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w
przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tego modułu na
własne ryzyko. |
Do zbudowania tego rozszerzenia nie są wymagane
żadne zewnętrzne biblioteki.
Chcąc używać tych funkcji musisz skompilować PHP z opcją --enable-overload.
Od PHP 4.3.0 to rozszerzenie jest włączone domyślnie. Możesz wyłączyć
wsparcie dla przeciążania opcją --disable--overload.
PHP w wersji dla systemów
Windows posiada wbudowaną obsługę dla tego rozszerzenia. Nie trzeba ładować
żadnych dodatkowych rozszerzeń aby korzystać z tych funkcji. Notatka:
Wsparcie dla przeciążania jest wbudowane od wersji PHP 4.3.0.
To rozszerzenie nie definiuje posiada żadnych
dyrektyw konfiguracyjnych w pliku php.ini. To rozszerzenie nie posiada żadnych rodzajów zasobów. To rozszerzenie nie posiada żadnych stałych.
Kilka prostych przykładów demonstrujących użycie funkcji
overload():
Przykład 1. Przeciążanie klasy PHP |
<?php
class OO
{
var $a = 111;
var $elem = array('b' => 9, 'c' => 42);
function __get($wl_nazwa, &$wl_wart)
{
if (isset($this->elem[$wl_nazwa])) {
$wl_wart = $this->elem[$wl_nazwa];
return true;
} else {
return false;
}
}
function __set($wl_nazwa, $wl_wart)
{
$this->elem[$wl_nazwa] = $wl_wart;
return true;
}
}
overload('OO');
$o = new OO;
print "\$o->a: $o->a\n"; print "\$o->b: $o->b\n"; print "\$o->c: $o->c\n"; print "\$o->d: $o->d\n"; $o->x = 56;
$val = new stdclass;
$val->prop = 555;
$o->a = array($val);
var_dump($o->a[0]->prop);
?>
|
|
| Ostrzeżenie |
Ponieważ jest to rozszerzenie eksperymentalne, nie wszystko działa.
Brakuje aktualnie wsparcia dla __call(), można
przeciążać tylko operacje pobierania i ustawiania właściwości obiektu.
Nie można także wołać funkcji obsługi przeciążania jak normalnych metod
istniejących w klasie, a __set() działa tylko do
jednego poziomu dostępu do właściwości.
|
- Spis treści
- overload -- Umożliwienie przeciążania właściwości i wołania metod dla klasy
User Contributed Notesdreamscape
29-Jun-2005 10:12
I didn't see this posted anywhere, so here it is:
In PHP 4, if you are calling your overloaded class A from inside class B, you MUST include and overload class A before including class B.
I struggled with this one for some time, before attempting to change the include order of the classes, which then worked great.
29-May-2005 12:38
> function __get($prop_name, &$prop_value)
Fatal error: [...] __get() must take exactly 1 argument ...
???
Shores
03-Feb-2005 07:11
One way to overcome the foreach overloading malfunction:
//non functioning:
foreach ($object->arrayProperty as $key => $value) { ... }
//functioning:
foreach (array_merge($object->arrayProperty) as $key => $value) { ... }
Bye!
evert at rooftopsolutions dot nl
17-Jan-2005 06:46
I use the overloader to perform a method-level permission check for objects
<?
class MyClass {
function method1() {
}
function method2() {
}
}
class ObjectProtector {
var $obj;
function ObjectProtector(&$object) {
$this->obj =& $object;
}
function __call($m,$a,&$r) {
if (myPermissionChecker(...)) {
$r = call_user_func_array(array($this->obj,$m),$a);
return true;
} else return false;
}
}
overload('ObjectProtector');
$myObj = new MyClass;
$myProtectedObj = new ObjectProtector($myObj);
$myProtectedObj->method1();
$myProtectedObj->method2('arguments');
?>
I'm not sure this is bad practice, but the engine allows it and it seems right.
koert at idislikespam dot bitfactory dot nl
29-Sep-2004 04:36
Do not implement __call() if you need pass-by-reference of return-by-reference elswhere in your class.
For more information view php bug #25831. Unfortunately this bug is marked wont-fix.
almethot at yahoo dot com
22-May-2004 09:33
Here is a cleaner way to fake overloading which is a modification on fabiostt[X_AT_X]libero[X_DOT_X]it
12-Aug-2003 01:56 posting. This example allows you to reuse the object and not have to re-create the object everytime the variables need to change.
Hope this helps,
<?
Class NCSession
{
Var $sessionResult = null;
function ncStartSession()
{
$numArgs = func_num_args() ; $args = func_get_args() ; $x = call_user_func_array( array( &$this, 'ncStartSession'.$numArgs), $args) ;
$sessionResult = $x;
return $sessionResult;
}
function ncStartSession0()
{
session_start();
$sessionResult = "SUCCESS|YES|SESSIONID|" . session_id();
session_destroy();
return $sessionResult;
}
function ncStartSession1($arg)
{
session_start($arg);
$sessionResult = "SUCCESS|YES|SESSIONID|" . session_id();
session_destroy();
return $sessionResult;
}
}
$myTestSession = NEW NCSession();
$myResult = $myTestSession->ncStartSession();
echo "\n\$myResult = $myResult\n";
?>
Metal
15-Mar-2004 08:11
Overload and Inheritance.
After wasting a few hours trying to get it to work, it seems appropriate to put a warning here.
Short Version:
DON'T ever subclass an overloaded class. EVER.
Corollary:
If an overloaded class simply must be subclassed, rewrite the parent class to get rid of the overloading. It can be as simple as commenting out the overload() statement and calling the get/set/call methods explicitely.
This was the road I ended up taking.
Long Version:
While it is, in theory, possible to end up with a working subclass, it requires much mucking and OO-principles compromise.
There is a great post that details the problem at great length. For those with the stomach, the URL is:
http://www.zend.com/lists/engine2/200201/msg00140.html
If you're still thinking about mixing inheritance and overloading, at least read the "Best Practices for the overload functions" in the URL above. If that doesn't change your mind, at least you'll be able to avoid most of the pitfalls.
josh at uncommonprojects dot com
28-Feb-2004 03:45
One thing about __get is that if you return an array it doesn't work directly within a foreach...
<?php
class Foo {
function __get($prop,&$ret) {
$ret = array(1,2,3);
return true;
}
}
overload ('Foo');
$foo = new Foo;
$bar = $foo->bar;
foreach($bar as $n) {
echo "$n \n";
}
foreach($foo->bar as $n) {
echo "$n \n";
}
?>
for loops also work fine..
upphpdoc at upcd dot de
25-Feb-2004 09:58
While this is a nice Feature it has nothing to do with Overloading as it is known in other OO-Languages.
What this feature does is allowing the dynamic addition of instance variables as e.g in Python.
Overloading means defining several methods with the same name in a single class. Which method will be called depends on the number and type of arguments specified. With dynamic and weak typed languages (like PHP) this can of course not work.
jw at jwscripts dot com
14-Feb-2004 08:10
The following backwards compatible code demonstrates the differences between the PHP version 4 and 5 implementation of overloading:
<?
class Foo {
var $array = array('a' => 1, 'b' => 2, 'c' => 4);
function __get($n, $val = "") {
if (phpversion() >= 5) {
return $this->array[$n];
} else {
$val = $this->array[$n];
return true;
}
}
function __set($n, $val) {
$this->array[$n] = $val;
if (phpversion() < 5) return true;
}
function __call($function, $arguments) {
if ($function != __CLASS__) {
$this->$arguments[0] = $arguments[1];
}
if (phpversion() < 5) return true;
}
}
if (function_exists("overload") && phpversion() < 5) {
overload("Foo");
}
$foo = new Foo;
$foo->set_array('c', 3);
$foo->c = 3;
echo 'The value of $foo->array["c"] is: ', $foo->c;
?>
sdavey at datalink dot net dot au
23-Jan-2004 10:45
It wasn't quite clear, but I found out that __get() and __set() only overload attributes that _don't_ exist.
For example:
<?
class Foo
{
var $a = "normal attribute";
function __get($key, &$ret)
{
$ret = "overloaded return value";
return true;
}
}
overload("Foo");
$foo = new Foo();
print "get a: $foo->a \n"; print "get b: $foo->b \n"; ?>
The important thing to note here is that $foo->a did not pass through __get(), because the attibute has been defined.
So it's more like "underloading" than "overloading", as it only virtualises attributes that _do not_ exist.
John Martin
09-Dec-2003 11:47
I've found a work around that allows overload to work with nested classes. I was trying to design a set of classes that I didn't need to define the setter/getter methods for each of the properties.
I stayed away from the __get() and __set() function since this bypasses object encapsulation. Instead I use the __call() method to implement the accessor functions. The __call() function emulates the get{var name} and stores the variable into an internal array with in the class. The get{var name} checks the array for the var name and returns it if found.
Using the Zend Dev Studio (Great Product!) I was able to debug the code and found that when overloaded objects are nested that the nested object somehow looses the array var. Just for giggles, I added a second variable and assigned the array var by reference. Some how this worked.
class Base {
var $_prop = array();
var $_fix;
function Base() {
// This somehow fixes the problem with nested overloading
$this->_fix = & $this->_prop;
}
}
admin (hat) solidox (dawt) org
25-Aug-2003 05:51
there are a couple of things you should be aware of when using overloading.
<?
class cTest
{
function __get($key, &$value)
{
echo "get: $key<br />";
return true;
}
function __set($key, $value)
{
echo "set: $key value: $value<br />";
return true;
}
function __call($method, $params, &$return)
{
echo "call: $method params: " . var_export($params, 1) . "<br />";
return true;
}
}
overload('cTest');
$cake = new cTest;
?>
firstly it should be noted that nested classes don't work.
secondly if you try to set an array it somehow becomes a get
and thirdly, if you call a nested class it picks the last nest as the method name, as opposed to a nested get which picks the first in the list.
<?
$x = $cake->hello->moto; $cake->hello['moto'] = 4; $cake->moo->cow("hello"); ?>
bit strange, these occur on php4.3.2. havn't tried other versions
Justin B
13-Aug-2003 12:16
Some useful things to know about overloading:
__call($m,$p,&$r) returns $r back to you, not whatever you put after the keyword return. What you return determines whether or not the parser consideres the function defined.
__get($var,&$val) returns $val back to you, so fill up $val with what you want then return true or false, same as above.
when extending classes, you must overload the most extended level class for it to work:
class TestClass
{
var $x = "x";
var $y = "y";
var $z = "z";
function __call($method,$params,&$return)
{
$return = "Hello, you called $method with ".var_export($params,true)."<br>\n";
return true;
}
function __get($var,&$val)
{
if($var == "l") { $val = $this->x; return true; }
return false;
}
}
overload('TestClass');
$test = new TestClass;
print $test->hello();
print $test->goodbye();
print $test->x;
print $test->l;
print $test->n;
class Test2 extends TestClass
{
}
$test2 = new Test2;
print $test2->hello();
/* output:
Hello, you called hello with array()
Hello, you called goodbye with array()
xx
Fatal Error: Call to undefined function hello() in ...
*/
fabiostt[X_AT_X]libero[X_DOT_X]it
12-Aug-2003 10:56
This extension has not much to do with overloading as we know it in Java or C++
We can sort of mimic overloading using call_user_func_array()
<?php
class OverloadTest{
var $message ;
function OverloadTest(){
$numArgs = func_num_args() ; $args = func_get_args() ; call_user_func_array( array( &$this, 'OverloadTest'.$numArgs), $args) ;
}
function overloadTest0(){
$this->message = 'There are no args' ;
}
function overloadTest1($arg){
$this->message = 'There\'s just one arg, its value is '.$arg ;
}
function overloadTest2($arg1, $arg2){
$this->message = 'There are 2 args, their values are '.join( func_get_args(), ', ') ;
}
function getMessage(){
return($this->message) ;
}
}$x = new OverloadTest('fooA', 'fooB') ;
echo( $x->getMessage() ) ;
?>
muell-spam-trash-abfall at kcet dot de
14-Mar-2003 04:53
This is the syntax of __get(), __set() and __call():
__get ( [string property_name] , [mixed return_value] )
__set ( [string property_name] , [mixed value_to_assign] )
__call ( [string method_name] , [array arguments] , [mixed return_value] )
__call() seems to work with PHP 4.3.0
See http://www.phppatterns.com/index.php/article/articleview/28/1/2/ for using this extension in detail.
steve at walkereffects dot com
25-Feb-2003 07:32
If you are a perfectionist when it comes to your class interfaces, and you are unable to use overload(), there is another viable solution:
Use func_num_args() to determine how many arguments were sent to the function in order to create virtual polymorphism. You can create different scenarios by making logical assumptions about the parameters sent. From the outside the interface works just like an overloaded function.
The following shows an example of overloading a class constructor:
class Name
{
var $FirstName;
var $LastName;
function Name($first, $last)
{
$numargs = func_num_args();
if($numargs >= 2)
{
$this->FirstName = $first;
$this->LastName = $last;
}
else
{
$names = explode($first);
$this->FirstName = $names[0];
$this->LastName = $names[1]
}
}
}
|