Home >Backend Development >PHP Problem >How to convert underline nomenclature to camel case nomenclature in PHP

How to convert underline nomenclature to camel case nomenclature in PHP

PHPz
PHPzOriginal
2023-04-11 10:33:031419browse

In PHP, we often encounter the need to convert strings with underscore_case to camelCase. For example, a database table field named "user_name" would be more suitable to use "userName" when converted to an object attribute.

The following is a common method:

function snakeToCamel($str, $capitalized = false) {
    $result = str_replace('_', '', ucwords($str, '_'));
    if (!$capitalized) {
        $result = lcfirst($result);
    }
    return $result;
}

This method uses the str_replace function and the ucwords function. The str_replace function is used to replace underscores in a string with an empty string, and the ucwords function is used to capitalize the first letter of each word. Finally, use the lcfirst function to lowercase the first letter of the first word to comply with camelCase requirements.

Next, we can use this method for setting and getting object properties:

class User {
    private $userId;
    private $userName;

    public function setUserId($userId) {
        $this->userId = $userId;
    }

    public function getUserId() {
        return $this->userId;
    }

    public function setUserName($userName) {
        $this->userName = snakeToCamel($userName);
    }

    public function getUserName() {
        return $this->userName;
    }
}

$user = new User();
$user->setUserId(123);
$user->setUserName('user_name');

echo $user->getUserId() . "\n";    // 输出:123
echo $user->getUserName() . "\n";  // 输出:userName

In the above example, we define a User class, where Contains two attributes: userId and userName. We use the setUserId and setUserName methods to set the values ​​of these two properties respectively, and use the getUserId and getUserName methods to get the values ​​of the properties. .

In the setUserName method, we use the snakeToCamel function mentioned above to convert the underscore named string into a camel case named string and assign it a value Give $userName attribute.

Using the above method, we can more conveniently process underscore-named strings and convert them into strings that meet the requirements of camel case naming, which improves the readability and maintainability of the code.

The above is the detailed content of How to convert underline nomenclature to camel case nomenclature in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn