首页 \ 问答 \ PHP类常量似乎总是被解释为字符串(PHP class constants seems to always be interpreted as strings)

PHP类常量似乎总是被解释为字符串(PHP class constants seems to always be interpreted as strings)

类常量似乎总是被解释为字符串,尽管它被定义为整数。 为什么PHP会做这种类型的杂耍,我该如何防止它?

请参阅以下代码:

class BitSet {
  const NONE = 0;
  const FOO = 1;
  const BAR = 2;
  const ALL = 3;

  public function __construct( $flags = self::NONE ) {
    if( $flags & self::ALL !== $flags )
      throw new \OutOfRangeException( '$flags = '.$flags.' is out of range' );
    $this->value = $flags;
  }

  protected $value = self::NONE;
}

$bs = new BitSet( BitSet::FOO );

最后一行(构造函数的调用)抛出OutOfRangeException

PHP Fatal error:  Uncaught exception 'OutOfRangeException' with message '$flags = 1 is out of range' in test-case.php:12
Stack trace:
#0 /srv/www/matthiasn/class-constant-debug.php(19): BitSet->__construct('1')
#1 {main}
thrown in /srv/www/matthiasn/class-constant-debug.php on line 12

正如你可以从backtrace条目#0清楚地看到的那样,常量BitSet::FOO作为字符而不是整数传递。 因此,位掩码操作$flags & self::ALL !== $flags不对整数执行,而是在按位ASCII表示上执行,因此失败。

我勒个去?! 有没有更好的方法来做到这一点,而不是到处做一个明确的(int)广播?


A class constant always seems to be interpreted as a string although it is defined as an integer. Why does PHP do this kind of type juggling and how do I prevent it?

See the following code:

class BitSet {
  const NONE = 0;
  const FOO = 1;
  const BAR = 2;
  const ALL = 3;

  public function __construct( $flags = self::NONE ) {
    if( $flags & self::ALL !== $flags )
      throw new \OutOfRangeException( '$flags = '.$flags.' is out of range' );
    $this->value = $flags;
  }

  protected $value = self::NONE;
}

$bs = new BitSet( BitSet::FOO );

The last line (the invocation of the constructor) throws the OutOfRangeException:

PHP Fatal error:  Uncaught exception 'OutOfRangeException' with message '$flags = 1 is out of range' in test-case.php:12
Stack trace:
#0 /srv/www/matthiasn/class-constant-debug.php(19): BitSet->__construct('1')
#1 {main}
thrown in /srv/www/matthiasn/class-constant-debug.php on line 12

As you can clearly see from backtrace entry #0 the constant BitSet::FOO is passed as a character not as an integer. Hence, the bit mask operation $flags & self::ALL !== $flags is not performed on integers but on the bitwise ASCII representation and therefore fails.

What the hell?! Is there any better way to get this right than to do an explicit (int)-cast everywhere?


原文:
更新时间:2022-02-07 21:02

最满意答案

您可以在表单中包含一个隐藏字段,指示提交的表单。

<form class="form" id="first_form" action="{{ urlFor('main.post') }}" method="post">
    <input type="hidden" name="which" value="first_form">
    // form data
</form>

<form class="form" id="second_form" action="{{ urlFor('main.post') }}" method="post">
    <input type="hidden" name="which" value="second_form">
    // form data
</form>

然后在您的路线中检查which输入的值。

$app->post('/main', function() use ($app) {
    $which = $app->request()->post('which')
    if ('first_form' === $which) {
        // do something
    } else if ('second_form' === $which){
        // do something else
    }
})->name('main.post');

You could include an hidden field in your form which indicates which form was submitted.

<form class="form" id="first_form" action="{{ urlFor('main.post') }}" method="post">
    <input type="hidden" name="which" value="first_form">
    // form data
</form>

<form class="form" id="second_form" action="{{ urlFor('main.post') }}" method="post">
    <input type="hidden" name="which" value="second_form">
    // form data
</form>

Then in your route check the value of which input.

$app->post('/main', function() use ($app) {
    $which = $app->request()->post('which')
    if ('first_form' === $which) {
        // do something
    } else if ('second_form' === $which){
        // do something else
    }
})->name('main.post');

相关问答

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)