Only variables should be passed by reference

后端 未结 12 1437
囚心锁ツ
囚心锁ツ 2020-11-22 06:14
// Other variables
$MAX_FILENAME_LENGTH = 260;
$file_name = $_FILES[$upload_name][\'name\'];
//echo \"testing-\".$file_name.\"
\"; //$file_name = strtolower
相关标签:
12条回答
  • 2020-11-22 06:31

    Assign the result of explode to a variable and pass that variable to end:

    $tmp = explode('.', $file_name);
    $file_extension = end($tmp);
    

    The problem is, that end requires a reference, because it modifies the internal representation of the array (i.e. it makes the current element pointer point to the last element).

    The result of explode('.', $file_name) cannot be turned into a reference. This is a restriction in the PHP language, that probably exists for simplicity reasons.

    0 讨论(0)
  • 2020-11-22 06:31

    PHP offical Manual : end()

    Parameters

    array
    

    The array. This array is passed by reference because it is modified by the function. This means you must pass it a real variable and not a function returning an array because only actual variables may be passed by reference.

    0 讨论(0)
  • 2020-11-22 06:32

    Everyone else has already given you the reason you're getting an error, but here's the best way to do what you want to do: $file_extension = pathinfo($file_name, PATHINFO_EXTENSION);

    0 讨论(0)
  • 2020-11-22 06:34

    Just as you can't index the array immediately, you can't call end on it either. Assign it to a variable first, then call end.

    $basenameAndExtension = explode('.', $file_name);
    $ext = end($basenameAndExtension);
    
    0 讨论(0)
  • 2020-11-22 06:36

    PHP complains because end() expects a reference to something that it wants to change (which can be a variable only). You however pass the result of explode() directly to end() without saving it to a variable first. At the moment when explode() returns your value, it exists only in memory and no variable points to it. You cannot create a reference to something (or to something unknown in the memory), that does not exists.

    Or in other words: PHP does not know, if the value you give him is the direct value or just a pointer to the value (a pointer is also a variable (integer), which stores the offset of the memory, where the actual value resides). So PHP expects here a pointer (reference) always.

    But since this is still just a notice (not even deprecated) in PHP 7, you can savely ignore notices and use the ignore-operator instead of completely deactivating error reporting for notices:

    $file_extension = @end(explode('.', $file_name));
    
    0 讨论(0)
  • 2020-11-22 06:40

    Since it raise a flag for over 10 years, but works just fine and return the expected value, a little stfu operator is the goodiest bad practice you are all looking for:

    $file_extension = @end(explode('.', $file_name));
    
    0 讨论(0)
提交回复
热议问题