Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
132 views
in Technique[技术] by (71.8m points)

javascript - Destructuring in php

Is it possible to use javascript like destructuring to create an associative array from variables with variable names as keys in PHP... in javascript I can do

 const fn = (name, age, purpose) => {
    return {name, age, purpose}
 }
 fn("Akins", 23, "Greatness") // {name: "Akins", age: 23, purpose: "Greatness"}

Currently I am stick to repetitive way

function fn($name, $age, $purpose) {
     return [
         'name'    => $name,
         'age'     => $age,
         'purpose' => $purpose
     ];
}

Can anyone help, it will save me a whole lot of typing?

question from:https://stackoverflow.com/questions/65925096/destructuring-in-php

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

There's no need to create your own function for this, one already exists:

$name    = "Jason";
$age     = 25;
$purpose = "To have fun?";

$person  = compact('name', 'age', 'purpose');

print_r($person);

Ouptut:

Array
(
    [name] => Jason
    [age] => 25
    [purpose] => To have fun?
)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...