Hi, I'm learning PHP and have ran into some confusion with the textbook I'm using, which had no errata support.
Executing the following example, from my textbook, seems to bypass the __set and __get accessor functions:
class classname
{
public $attribute;
function __get($name)
{
return $this->$name;
}
function __set ($name, $value)
{
if(($name == "attribute") && ($value >= 0) && ($value <= 100)){
$this->attribute = $value;
}
}
}
$a = new classname();
$a->attribute = 500;
echo $a->attribute;
But when I change the access modifier to "private" it seems to work ok, and use the.
Can someone tell me what it is supposed to be?
Many thanks.
__get() __set()
Moderator: General Moderators
Re: __get() __set()
Code: Select all
<?php
class classname
{
private $attribute;
function __get($name)
{
return $this->$name;
}
function __set ($name, $value)
{
if(($name == "attribute") && ($value >= 0) && ($value <= 100)){
$this->attribute = $value;
} else {
throw new Exception("Object does not allow variable: $name to be set with value: $value");
}
}
}
$a = new classname();
try {
$a->attribute = 99;
//$a->attribute = 500;
echo $a->attribute;
} catch (Exception $e) {
print_r($e);
}Generally speaking, all variables should be protected or private as this is really at the heart of the encapsulation theory of OOP. When you use a variable that needs to be manipulated, make sure to code a setVariable() function. Likewise when you have a varaible that needs to be echoed or used outiside of its class or in another class, code a getVariable() function.
__set and __get are not functions that should be included in every class.
If I didn't answer well enough, let me know what is still confusing.
Re: __get() __set()
Many, many thanks for the clariffication.
This is what I had thought, but, as I'm only learning, I presumed the book I am studying from, "PHP and MySQL Web Development" by Luke Welling and Laura Thomson, would be authoritative. As it turns out, the book is full of errors and misguided information, leaving one totally discouraged.
Many thanks again.
This is what I had thought, but, as I'm only learning, I presumed the book I am studying from, "PHP and MySQL Web Development" by Luke Welling and Laura Thomson, would be authoritative. As it turns out, the book is full of errors and misguided information, leaving one totally discouraged.
Many thanks again.
Re: __get() __set()
No problem.
One of the best beginner's books is "PHP A Beginner’s Guide" by Vikram Vaswani.
One of the best beginner's books is "PHP A Beginner’s Guide" by Vikram Vaswani.