怎樣優雅地拼湊字串?

來源:互聯網
上載者:User
$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]) );

存數組遍曆唄

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.