Re: OOP: class variables question
| From: | Teodor Cimpoesu | Date: | Sat, 11 Nov 2000 16:54:43 +0000 |
| Subject: | Re: OOP: class variables question | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-24786@lists.php.net to get a copy of this message | ||
Hi Chris!
On Thu, 09 Nov 2000, Chris Carbaugh wrote:
>
> I ran into a clash between class variables today. I entended a class,
> and in the new class I created a variable with the same name that the
> original class defined. This of course corrupted the data in the
> varible(s).
>
> Here's a sample:
>
> class A {
> var $data = "foo";
>
> function dofoo(){
> // do something with $data
> }
> }
>
> class B extends A {
> var $data = "bar";
>
> function dobar(){
> // do something with $data
> }
> }
>
> Now class A expects it's $data not be messed with by outsiders.
> Class be (the outsider) doesn't know class A uses $data, and changes
> it.
> Or class B calls a method defined in A which uses A's definition of
> $data, thereby corrupting B's definition of $data.
>
> Am I making sense here?
>
> I have only read a little about OPP in languages like C++, but I think
> this is the point of public/private variables?
usually this also happens in C++:
#include <iostream>
class A { public: static int i; int j; A():j(3){}};
int A::i = 1;
class B:public A { public: static int i;int j; B():j(4){} };
int B::i = 2;
void main() { B b;
cout<<"b.i="<<b.i<<",b.j="<<b.j<<endl<<"A::i
= "<<A::i;}
prints:
b.i=2,b.j=4 // A::j is gone by now
A::i = 1
In PHP we don't have the notion of 'class attribute', so you can't use A::i
trick, and also I think the derivation in PHP would overwrite the A::i
memeber.
Now, what I remember about an old 'private vars' thread on php-dev
was that somebody (Mathew Kooiman? don't remember, or somebody from France
I think) implemented a patch to allow private members, then Zeev said
he will implemented it in a later version (again, iirc).
The issue was the added overhead, and my suggestion at that time was to use
python way of rewriting variable names, which in your examples it would look
like
when one writes:
class A { var $__data = "foo" ; }
class B extends A { var $__data = "foo" ; }
the actual translation of the code would be into:
class A { var $_A__data = "foo" ; }
class B extends A { var $_B__data = "foo" ; }
so until this is implemented (or something else) you can write it by hand :)
-- teodor