Rumah >pembangunan bahagian belakang >tutorial php >怎样优雅地拼凑字符串?

怎样优雅地拼凑字符串?

WBOY
WBOYasal
2016-06-06 20:35:081051semak imbas

<code>$username = $this->username ?: 'someone';
$email = $this->email ?: Yii::$app->params['adminEmail'];
$password = Yii::$app->getSecurity()->generatePasswordHash(
    $this->password ?: 'xx'
);

$table = User::tableName();
$auth_key = Yii::$app->security->generateRandomString();
$status = User::STATUS_ACTIVE;
$timestamp = time();
$god = 1;

$words  = "in the ${table} has a record which contains some value : ";
$words .= "'${username}', '${email}', '${password}', '${auth_key}', '${status}','${timestamp}', '${god}', '${timestamp}', '${god}' ";
</code>

上面的 word 怎样拼凑才能优雅些?

回复内容:

<code>$username = $this->username ?: 'someone';
$email = $this->email ?: Yii::$app->params['adminEmail'];
$password = Yii::$app->getSecurity()->generatePasswordHash(
    $this->password ?: 'xx'
);

$table = User::tableName();
$auth_key = Yii::$app->security->generateRandomString();
$status = User::STATUS_ACTIVE;
$timestamp = time();
$god = 1;

$words  = "in the ${table} has a record which contains some value : ";
$words .= "'${username}', '${email}', '${password}', '${auth_key}', '${status}','${timestamp}', '${god}', '${timestamp}', '${god}' ";
</code>

上面的 word 怎样拼凑才能优雅些?

sprintf是个不错的方案

不过看你的代码感觉就是像把各种变量都打出来调试用,那么有个神器 get_defined_vars,变量名变量值都有了你值得拥有

一句话,尽量使用 ORM 或者 数据库类 去操作数据库,而不要人工拼凑字符串,这样能有效防止 SQL注入 的发生。Yii 框架肯定是自带这些东西的,你上文档好好看看就好啦:http://www.yiiframework.com/doc/guide/1.1/en/database.dao#binding-para...

如果是单纯的拼接字符串的话一般情况下双引号内直接写变量名(不用花括号)就可以了,当然介于那个字段的拼接实在是有点丑你可以这么改写一下:

<code>$words = "in the $table has a record which contains some value: ";
$words .= implode(", ", array_map(function($item) {
    return "'$item'";
}, [$username, $email, $password, $auth_key, $status, $timestamp, $god]) );
</code>

存数组遍历呗

Kenyataan:
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn