当前位置:Gxlcms > PHP教程 > 怎样优雅地拼凑字符串?

怎样优雅地拼凑字符串?

时间:2021-07-01 10:21:17 帮助过:3人阅读

$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}' ";

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

回复内容:

$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}' ";

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

sprintf是个不错的方案

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

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

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

$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]) );

存数组遍历呗

人气教程排行