Skip to content

Instantly share code, notes, and snippets.

@zjsxwc
Created April 27, 2023 01:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zjsxwc/970216c64d7cc5905e86a0d17f62bbb2 to your computer and use it in GitHub Desktop.
Save zjsxwc/970216c64d7cc5905e86a0d17f62bbb2 to your computer and use it in GitHub Desktop.
php取到调用时实参位置的内容
<?php
/**
* @param int $argPos
*/
function getArgName($argPos) {
$db = debug_backtrace();
$fileStr = file_get_contents($db[1]["file"]);
$lineList = explode("\n", $fileStr);
$line = trim($lineList[$db[1]["line"] - 1]);
$funCallStr = $db[1]["function"]."(";
$funCallPos = strpos($line, $funCallStr);
$argsStr = substr($line, $funCallPos+strlen($funCallStr));
// $argsStr = '$user , ssd() ,dd3(dd4($ff(),gg())) );';
$c = 0;
$currentLv = 0;
$lv0ArgList = [];
$currentLv0Arg = "";
while (1) {
if ($argsStr[$c] === "(") {
$currentLv += 1;
$currentLv0Arg .= $argsStr[$c];
}
elseif ($argsStr[$c] === ")") {
$currentLv -= 1;
$currentLv0Arg .= $argsStr[$c];
if ($currentLv <= 0) {
if ($currentLv === 0) {
$lv0ArgList[] = trim(trim($currentLv0Arg), ", \t\n\r\0\x0B");
} else {
$lv0ArgList[] = trim(trim($currentLv0Arg), "), \t\n\r\0\x0B");
}
$currentLv0Arg = "";
}
}
elseif ($argsStr[$c] === ",") {
$currentLv0Arg .= $argsStr[$c];
if ($currentLv === 0) {
if (trim($currentLv0Arg) !== ",") {
$lv0ArgList[] = trim(trim($currentLv0Arg), ", \t\n\r\0\x0B");
$currentLv0Arg = "";
}
}
} else {
$currentLv0Arg .= $argsStr[$c];
}
if ($currentLv < 0) {
break;
}
$c++;
if ($c >= strlen($argsStr)) {
break;
}
}
return $lv0ArgList[$argPos];
}
function test($xcc, $str) {
var_dump($str);
$strArgPos = 1;
$argName = getArgName($strArgPos);
var_dump($argName);
}
$user = "xxx";
$xxx2 = function () use ($user) {
test(222/*test*/, $user/*test*/);
};
$xxx2();
/*
*输出
$php getArgName.php
string(3) "xxx"
string(13) "$user/*test*/"
*/
@zjsxwc
Copy link
Author

zjsxwc commented Apr 27, 2023

代码的限制是

  • 函数调用必须在一行以内,不能写成多行。
  • 函数调用只认那一行第一次调用。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment