user1782145
user1782145

Reputation: 31

Annoying PHP error: "Strict Standards: Only variables should be passed by reference in"

I have this small script made and I cant get this error:

Strict Standards: Only variables should be passed by reference in C:\xampp\htdocs\includes\class.IncludeFile.php on line 34" off!

Here is the page:

namespace CustoMS;

if (!defined('BASE'))
{
    exit;
}

class IncludeFile
{
    private $file;
    private $rule;

    function __Construct($file)
    {
        $this->file = $file;

        $ext = $this->Extention();
        switch ($ext)
        {
            case 'js':
                $this->rule = '<script type="text/javascript" src="'.$this->file.'"></script>';
                break;

            case 'css':
                $this->rule = '<link type="text/css" rel="stylesheet" href="'.$this->file.'">';
                break;
        }
    }

    private function Extention()
    {
        return end(explode('.', $this->file));
    }

    function __Tostring()
    {
        return $this->rule;
    }
}

Please help me.

Upvotes: 3

Views: 5488

Answers (2)

Leri
Leri

Reputation: 12525

function end has following prototype end(&$array).

You can avoid this warning by creating variable and pass it to function.

private function Extention()
{
    $arr = explode('.', $this->file);
    return end($arr);
}

From the documentation:

The following things can be passed by reference:

  • Variables, i.e. foo($a)
  • New statements, i.e. foo(new foobar())
  • References returned from functions, i.e.:

explode returns an array not a reference to array.

For example:

function foo(&$array){
}

function &bar(){
    $myArray = array();
    return $myArray;
}

function test(){
    return array();
}

foo(bar()); //will produce no warning because bar() returns reference to $myArray.
foo(test()); //will arise the same warning as your example.

Upvotes: 6

Matthieu Napoli
Matthieu Napoli

Reputation: 49703

private function Extention()
{
    return end(explode('.', $this->file));
}

end() sets the pointer array to the last element. Here you are providing the result of a function to end rather than a variable.

private function Extention()
{
    $array = explode('.', $this->file);
    return end($array);
}

Upvotes: 1

Related Questions