PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!
hi to all!
i have a couple of newbie questions that are tantalizing me:
1. is there a way to do multiple operations (like variable assigaments and using functions) with an object without writing it fully over and over? Ex:
class foo {
function bar() { }
}
$foobar=new foo;
//foobar only has the function bar(), but i want it to have a baar() function too
pistacchio wrote:
1. is there a way to do multiple operations (like variable assigaments and using functions) with an object without writing it fully over and over? Ex:
$foo->color="violet";
$foo->name="flower";
$foo->scent="good";
// to become:
with $foo do {
color="violet";
name="flower";
scent="goo";
}
Not in PHP4, not in PHP5 perhaps.
pistacchio wrote:
2. once i've created an object from a class, can i add a function to that object that is not directly defined by the class? Ex:
class foo {
function bar() { }
}
$foobar=new foo;
//foobar only has the function bar(), but i want it to have a baar() function too
no, but you can use variable variables or function handling functions to simulate such behavior:
class a {
var $b;
function a($b=null) {
$this->b = $b;
}
function some() {
if(!is_null($this->b)&&is_callable($this->b)) {
$callback = $this->b;
$callback($this);
}
// do something....
}
}
function cb($obj) {
var_dump($obj);
}
$q = new a('cb');
$q->some();
class a {
var $callbacks = array();
function a() {}
function add_callback($cb) {
$this->callbacks[] = $cb;
}
function some() {
foreach($this->callbacks as $callback) {
if(is_callable($callback))
call_user_func($callback, $this);
}
}
}
$q = new a;
function e($obj) {
var_dump($obj);
}
function f($obj) {
echo "Class name is: ". get_class($obj) . "\n";
}
$q->add_callback('e');
$q->add_callback('f');
$q->some();