在父函数中使用子函数中的变量集

Use variable set in child function in Parent function

假设我有一个子函数。

function hello {
$x= 1
$y = 2;    
}

function outerFunction {

hello

$z = $x + $y

}

有没有办法做到这一点?

您可以使用Dot sourcing operator .hello函数范围内定义的变量带入outerFunction函数范围:

function hello {
    $x = 1; $y = 2
}

function outerFunction {
    . hello
    $x + $y
}

outerFunction # => 3

您还可以根据不涉及操作员的用例考虑不同的替代方案。例如:

function hello {
    1, 2
}

function outerFunction {
    $x, $y = hello
    $x + $y
}

outerFunction