To alleviate some confusion, I’ve completely re-written this question.
Here is the controller:
<?php
class StaffController extends AppController{
function test(){
$this->data = $this->Staff->find( 'list' );
}
}
Here is the entire view:
<pre>
Count: <?php echo count( $this->data ) . "\n"; ?>
Empty: <?php echo ( empty( $this->data ) ? 'true' : 'false' ) . "\n"; ?>
Count: <?php echo count( $this->data ) . "\n"; ?>
<?php var_dump( $this->data ) ?>
</pre>
Here is the rendered output:
Count: 2
Empty: true
Count: 2
array(2) {
[1]=>
string(12) "Mock Staff 1"
[2]=>
string(12) "Mock Staff 2"
}
Why would empty() return True when both count() and debug() show that a non-empty value has been assigned?
Is this a CakePHP bug? A PHP bug? ???
If I use another variable instead of $this->data :
function test(){
$this->set( 'data', $this->Staff->find( 'list' ) );
}
And the view:
<pre>
Count: <?php echo count( $data ) . "\n"; ?>
Empty: <?php echo ( empty( $data ) ? 'true' : 'false' ) . "\n"; ?>
Count: <?php echo count( $data ) . "\n"; ?>
<?php var_dump( $data ) ?>
</pre>
it works as expected:
Count: 2
Empty: false
Count: 2
array(2) {
[1]=>
string(12) "Mock Staff 1"
[2]=>
string(12) "Mock Staff 2"
}
Any takers?
$this->datais special in Cake views. When you access$this->datain a view, you actually end up calling the magic methodView::__get(), andempty()doesn’t work with methods or functions–it only works with variables. As you’ve found, the correct way to pass data to a view is by using$this->set()in your controller. Just to clarify,$thisin the view is a different object than$thisin your controller.