问题描述
那么PHP中的$variable
有多大?我已经尝试过测试,但是不确定是否有足够的系统内存(〜2gb).我认为必须有某种限制.字符串太大时会发生什么?它是串联的,还是PHP抛出异常?
So how big can a $variable
in PHP get? I've tried to test this, but I'm not sure that I have enough system memory (~2gb). I figure there has to be some kind of limit. What happens when a string gets too large? Is it concatenated, or does PHP throw an exception?
推荐答案
http ://php.net/manual/en/language.types.string.php 说:
在PHP 5.x中,字符串被限制为2 -1个字节,因为内部代码将长度记录为带符号的32位整数.
In PHP 5.x, strings were limited to 2-1 bytes, because internal code recorded the length in a signed 32-bit integer.
例如,您可以使用 file_get_contents()
You can slurp in the contents of an entire file, for instance using file_get_contents()
但是,PHP脚本在给定脚本执行中可以分配给所有变量的总内存受到限制,因此这实际上也限制了单个字符串变量的长度.
However, a PHP script has a limit on the total memory it can allocate for all variables in a given script execution, so this effectively places a limit on the length of a single string variable too.
此限制是php.ini配置文件中的memory_limit
指令.内存限制在PHP 5.2中默认为128MB,在早期版本中为8MB.
This limit is the memory_limit
directive in the php.ini configuration file. The memory limit defaults to 128MB in PHP 5.2, and 8MB in earlier releases.
如果您没有在php.ini文件中指定内存限制,它将使用默认值,该默认值将被编译到PHP二进制文件中.从理论上讲,您可以修改源代码并重建PHP来更改此默认值.
If you don't specify a memory limit in your php.ini file, it uses the default, which is compiled into the PHP binary. In theory you can modify the source and rebuild PHP to change this default value.
如果在php.ini文件中将-1
指定为内存限制,它将停止检查并允许脚本使用操作系统分配的内存.这仍然是一个实际的限制,但是取决于系统资源和体系结构.
If you specify -1
as the memory limit in your php.ini file, it stop checking and permits your script to use as much memory as the operating system will allocate. This is still a practical limit, but depends on system resources and architecture.
来自@ c2的评论:
这是一个测试:
<?php
// limit memory usage to 1MB
ini_set('memory_limit', 1024*1024);
// initially, PHP seems to allocate 768KB for basic operation
printf("memory: %d\n", memory_get_usage(true));
$str = str_repeat('a', 255*1024);
echo "Allocated string of 255KB\n";
// now we have allocated all of the 1MB of memory allowed
printf("memory: %d\n", memory_get_usage(true));
// going over the limit causes a fatal error, so no output follows
$str = str_repeat('a', 256*1024);
echo "Allocated string of 256KB\n";
printf("memory: %d\n", memory_get_usage(true));
这篇关于PHP中字符串的最大长度是多少?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!