compact has access to these variables because they are in local scope (inside the function braces):
function call_me_compact() {
// vvv Function Scope vvv
$name = "my_name";
$age = 100;
return compact("name", "age"); // put variables from local scope into [array]
// ^^^ Function Scope ^^^
}
In your second example, you are calling a function with two strings and they are accessible in the $args list, take a look:
function my_compact_function(...$args) {
print_r($args);
}
function call_me() {
$name = "my_name";
$age = 100;
return my_compact_function("name", "age");
}
// yielding: $args = [
// [0] => name
// [1] => age
// ]
The compact function actually returns a hashed array of variable names, and their values from local scope (via introspection).