【问题标题】:Use public functions inside a public function在公共函数中使用公共函数
【发布时间】:2016-03-09 08:41:50
【问题描述】:

是否可以在 php 的公共函数中使用公共函数?

我有一些公共函数可以改变输入并返回它。我想在循环我的函数的公共函数中创建一个 for 语句,例如:

$input

for= function1 -> output1 -> function2->output2->function3->output3.

我想将它的输出用于我的下一个函数。我的 for 循环中的 4 个函数也必须循环 9 次。

在这种情况下,它与 AES 加密有关。我得到了 4 个函数:subBytes、shiftRows、mixColumns、addRoundkey。

这是我的公共函数加密:

public function encrypt($input)
{
    $functions= ('subBytes', 'shiftRows', 'mixColumns', 'addRoundKey' );
    foreach($functions as $function)
    {
        $input = $$function($input);
    }

    return($input);
} //end function encrypt

这是我的功能之一:

public function subBytes($state)
{
    for ($row=0; $row<4; $row++){ // for all 16 bytes in the (4x4-byte) State
        for ($column=0; $column<4; $column++){ // for all 16 bytes in the (4x4-byte) State
            $_SESSION['debug'] .= "state[$row][$column]=" . $state[$row][$column] ."-->" . self::$sBox[$state[$row][$column]]."\n";
            $state[$row][$column] = self::$sBox[$state[$row][$column]];
        }
     }
     return $state;
}

【问题讨论】:

  • public function blabla() 表示类的方法。只要它不是static 方法,就需要使用对象调用它。你不能只叫它subBytes(),你可能想要$this-&gt;subBytes()。在运行时生成函数名称时,您可以使用this answer 中提供的解决方案,或者,对于更复杂的情况(动态列表或参数,例如),您可以使用函数call_user_func(),将array($this, $function) 作为其第一个参数。

标签: php loops for-loop


【解决方案1】:

使用这样的代码:

$output3 = function3(function2(function1($input)));

或者您可以将您的函数名称添加到数组中并对其进行迭代:

$input = ''; // some value
$functioins = ('function1', 'function2', 'function3', 'function4');
foreach ($functions as $function) {
    $input = $$function($input);
}
$output = $input;

如果我们尝试使用对象的公共函数,那么:

public function encrypt($input)
{
    // array with methods names
    $methods= array('subBytes', 'shiftRows', 'mixColumns', 'addRoundKey' );
    foreach($methods as $method)
    {
        $input = $this->$method($input);
    }

    return($input);
}

【讨论】:

  • 它对函数管道的创建有何影响?您可以使用此方法将每个先前函数的输出与后续函数的输入连接起来。好的,我看看更新的问题
  • 为对象的公共功能尝试第二个版本
  • 我在实现您的代码时收到以下错误:解析错误:语法错误,意外 ',' in C:\wamp\www\aes.php 第 114 行 $methods 行中的内容是不正确。
  • 添加到您的 114 行的注释中,因为该字符串有错误,public function encrypt 的此代码也完全没有语法错误
  • 我暂时更改了数组,只更改了第一步:subBytes .. 这个有效!我得到一个输出,现在我需要将该输出用于我的下一个功能.. public function encrypt($input) { // array with methods names $methods= array('subBytes'/*, 'shiftRows', 'mixColumns', 'addRoundKey' */); foreach($methods as $method) { $input = $this-&gt;$method($input); } return($input);
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-09-13
  • 2019-11-23
  • 2023-03-08
  • 2012-04-08
  • 2016-01-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多