Not for 'how-to' coding questions but PHP theory instead, this forum is here for those of us who wish to learn about design aspects of programming with PHP.
class kQuery{
function __construct(){
// no arguments? return a blank kQuery object
if(func_num_args()==0) return $this;
// what arguments are there?
$a = func_get_args();
// testing the variable number of arguments
foreach($a as $arg) echo '<br/>'.$arg;
// return the kQuery object
return $this;
}
function test(){
$a=func_get_args();
echo '<br/>this is a '.implode(', ',$a).' kQuery object!';
return $this;
}
}
// assign the kQuery object maker
$k = create_function('','$args=func_get_args(); return call_user_func_array(array(new kQuery(),"__construct"),$args);');
// perform a (very) simple POC test:
$k('bob','frank')->test('super','krazy')->test('groovy','radical');
<?php
ini_set('display_errors', true);
assert_options(ASSERT_ACTIVE, true);
assert_options(ASSERT_WARNING, true);
class Foo
{
public function __construct($a)
{
$this->bar = $a;
return $a + 5;
}
}
$a = new Foo(5);
assert($a->bar == 5);
assert($a->__construct(4) == 9);
assert($a->bar == 4);
I'd definitely say its a bad idea though, readability-wise. Constructors are for creating instances not for whatever funky stuff you are trying to do there kieran.
Constructors are supposed to return a reference to the newly created object and thats it. I am suprised it doesn't explode when you try to do it. I would definitely not code something to rely on returning something special from a constructor as that is liable to break at some point.
<?php
class Test_This
{
private $class_var;
public function __construct()
{
$this->class_var = 'I am now set!';
return $this->class_var;
}
}
$test_class = new Test_This;
?>
Is $test_class an object of the Test_This class, or is it the string value assigned to $test_class upon instantiation? It just seems like a conflict to me, even if it is not really a conflict. You know what I mean?
I guess it doesn't make a difference in my case since I'm always returning the object itself, which is the purpose of the constructor anyway, isn't it?
The purpose of the constructor is to initialize the object only. Nothing more. They are not supposed to return anything because they are automatically called during the invocation of the "new" operator.
feyd wrote:The purpose of the constructor is to initialize the object only. Nothing more. They are not supposed to return anything because they are automatically called during the invocation of the "new" operator.
Oops meant to quote Kieran:
Kieran Huggins wrote:I guess it doesn't make a difference in my case since I'm always returning the object itself, which is the purpose of the constructor anyway, isn't it?
But your constructor is not really returning anything -- new is.
Last edited by Christopher on Mon Mar 12, 2007 1:28 am, edited 1 time in total.