tags:

views:

42

answers:

2
<?php
class Conversor {
 function toLowerFirst($word) {
  $word = 'test';
  return $word;
 }
}

class Test {
 function test() {
  $word = 'Test';
  $word = $this->conversor->toLowerFirst($word);
  echo $word;
 }
}

class Launcher {
 function launch() {
  $Test = new Test();
  $Test->conversor = new Conversor();
  $Test->test();
 }
}

$launcher = new Launcher();
$launcher->launch();
?>

Why doesn't it echo 'test'?

+5  A: 

It's because your function test() is the same as the class name - it looks like an old-style constructor, so it's being run when you do new Test(), i.e. before you set conversor.

Rename the function or add a new-style constructor to Test: __construct()

Greg
I thought starting with a t in the function and T in the class were going to differentiate them.
Delirium tremens
Unfortunately not :)
Greg
+1  A: 

Because the call $word = $this->conversor->toLowerFirst($word); returns an error, the function toLowerFirst doesn't exist at that time (you call the function through a non-existant instance of Conversor)

Replace $word = $this->conversor->toLowerFirst($word); with $word = Conversor::toLowerFirst($word); and it will work.

Edit: the __construct is a better solution, because my suggestion results in 2 times the echo.. (test is treated as a constructor for Test)

MysticEarth
@Delirium tremens, this is the reason! Nice answer MisticEarth. That said maybe you should re-think the flow of the program as this will probably throw a Strict Standards warning.
Frankie
In the unsimplified code, the part that corresponds to $word = $this->conversor->toLowerFirst($word); runs before the part that corresponds to $Test->conversor = new Conversor(); runs.
Delirium tremens