PHP4 Class features
| From: | Vamsi Nath | Date: | Tue, 04 Apr 2000 22:19:30 +0000 |
| Subject: | PHP4 Class features | ||
| Groups: | php.version4 | ||
| Request: | Send a blank email to php-version4+get-13123@lists.php.net to get a copy of this message | ||
I've been playing around with some of the object-oriented features in PHP4 in conjunction with
a C++ class I have been taking and I've noticed some differences in the class implementation
between the two. I realize that this is to be expected and that PHP is not intended to be the most
robust OOP environment.
One thing I've noticed is that PHP classes seem to have no concept of 'data hiding'.
Anyone familiar with C++ knows that data members of a class are only accessible by the class's
member functions or specifically defined FRIEND functions, which PHP doesn't seem to support
either. However, it seems that in PHP any non-member function can access and change any
object's data members.
For example if we have a class like:
class Test {
var $a
var $b
#Our default constructor
function Test($a=1, $b=2) {
$this->a = $a;
$this->b = $b;
}
function print_it() {
print "$this->a<br>$this->b\n";
}
}
We can define another function outside of the class which can modify a member value:
function set_member(&$object, $val) {
$object->a = $val;
}
Notice we are passing the object by reference. Then we can do the following:
$myObj = new Test;
set_member($myObj, 6);
$myObj->print_it();
If you do this, you will see that the set_member() function has changed the value of $a for our
object to 6. Correct me if I'm wrong, but this would not be possible in C++ unless set_member()
was explicitly defined as a FRIEND function in our class definition.
I apologize for the length of this email, but I am curious if this behavior is by design and if so,
what the rational behind this implementation is. It seems to me that class member data should be
protected from tampering by non-member functions.
Thanks,
Vamsi Nath