引号内的变量名前面的冒号(:)如何工作?

nim*_*ble 2 php yii

我假设:parent_id评估为一个数字.但是,这段代码究竟是如何工作的呢?我什么时候应该使用这种语法(:name)?

$data = Location::model()->findAll('parent_id=:parent_id',array(
                ':parent_id' => (int) $_POST['Current-Controller']['country_id']
        ));
Run Code Online (Sandbox Code Playgroud)

Jon*_*Jon 8

冒号没有任何特殊含义.整个模式:parent_id确实如此,但这只是因为您选择在WHERE条件(parent_id=:parent_id)中将其用作变量名.

你也可以选择写作

$data=Location::model()->findAll('parent_id=the_quick_brown_fox',
     array('the_quick_brown_fox'=>(int) $_POST['Current-Controller']['country_id']));
Run Code Online (Sandbox Code Playgroud)

在实践中使用冒号是因为您为变量选择的名称也存在作为条件的合法部分存在的风险,在这种情况下,它的所有实例都将替换为值,结果将是意外的.

例如,这个:

$data=Location::model()->findAll('parent_id=parent_id',
     array('parent_id'=> 1 /*anything, really*/));
Run Code Online (Sandbox Code Playgroud)

会导致条件1=1,这将匹配所有记录.