![]() |
Is referencing a class bad practice?
Just wondering is referencing a class in another class bad? Like so
PHP Code:
PHP Code:
|
|
Heh, Thats good to know.
Just wondering though. Could the way the server's configured make it act differently? I mean i've developed a script locally and it works fine then i've put it on a web server and its not working properly. how i mean is i'm referencing a class and then in a function passing some data to an array in the referenced class. Then back on the main page it called to a functio on the class that was passed data to and the data doesn't seem to be there. Any idea why it would do this? |
The statement "Then back on the main page", sounds like you're trying to keep the class data alive during page reloads, is this the case?
|
No, Here's an example.
index.php PHP Code:
PHP Code:
PHP Code:
|
That is very strange, what version of PHP is the server using?
|
Tis indeed strange, it works fine for me
|
This thread doesn't need another "me too", but it's going to get one anyway! It works for me as well. I guess it all comes to the PHP version, although even still it's still very bizarre.
|
Pre-PHP 5 when you refer to a class in a function call, without using the ampersand operator then PHP would clone the class and not simply pass a reference as you are hoping for.
your code: PHP Code:
PHP Code:
|
Quote:
And i tried adding the ampersand but still got the same outcome. As this needs to be done soon i have worked around it by returning the data and then calling to the template functions but this was quite a pain :p Thanks all ^^ |
There's a very simple solution.
Change: (in the class2 constructor) PHP Code:
PHP Code:
&$class1 argument for the constructor ensured that the argument was brought in by reference, but when it was being assigned to the class1 property the assignment was by value -- a copy of the object was made and assigned to the property. When we changed the data property, it was only changing it in the copy and not the original. Using =& the variable is assigned by reference as we intended. Hopefully you can see now why this behaviour was changed in PHP5 to assign by reference by default. :) |
Quote:
Works perfectly. Greatly appriciated :D. Thanks very much :) |
| All times are GMT. The time now is 09:13 PM. |
Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.1.0