混乱を緩和するため、この質問を完全に書き直しました。
ここにコントローラがあります:
<?php
class StaffController extends AppController{
function test(){
$this->data = $this->Staff->find( 'list' );
}
}
全体ビューは次のとおりです:
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 ) ?>
レンダリングされた出力は次のとおりです。
Count: 2
Empty: true
Count: 2
array(2) {
[1]=>
string(12) "Mock Staff 1"
[2]=>
string(12) "Mock Staff 2"
}
count()
と
debug()
の両方に空でない値が割り当てられていると表示された場合、
empty()
はTrueを返します。
これはCakePHPのバグですか? PHPのバグ? ???
If I use another variable instead of $this->data :
function test(){
$this->set( 'data', $this->Staff->find( 'list' ) );
}
とビュー:
Count: <?php echo count( $data ) . "n"; ?>
Empty: <?php echo ( empty( $data ) ? 'true' : 'false' ) . "n"; ?>
Count: <?php echo count( $data ) . "n"; ?>
<?php var_dump( $data ) ?>
それは期待どおりに動作します:
Count: 2
Empty: false
Count: 2
array(2) {
[1]=>
string(12) "Mock Staff 1"
[2]=>
string(12) "Mock Staff 2"
}
何かお手数ですか?
ベストアンサー
$this->data
is special in Cake views. When you
access $this->data
in a view, you actually end up
calling the magic method View::__get()
, and
empty()
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, $this
in the view is a
different object than $this
in your controller.