I am using php 7. I have a php code
as shown below in which when user enters all 5 values in both text fields at Line B
and Line C
and hit the save button at Line D
, I am
getting the error "Only variables should be passed by reference at Line A
".
The goAhead()
method is inside the class SapDiagram
in def.php file below.
abc.php
<?php
$diagram = &$_SESSION['sap']->diagrams[$index];
if ('POST' == $_SERVER['REQUEST_METHOD']) {
for ($i = 0, $used = 0; 5 > $i; ++$i) {
if (!empty($_POST["normal$i"]) && !empty($_POST["wrap$i"])) {
$diagram->goAhead(new SapFile($_POST["normal$i"], $_POST["wrap$i"]), $used++); // Line A
}
}
}
?>
<html>
<head>
<title>Good World</title>
</head>
<body>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<?php
for ($i = 0; 5 > $i; ++$i) {
?>
<fieldset>
<input type="text" name="normal<?php echo $i; ?>"
value="<?php echo isset($diagram->files[$i]) ? $diagram->files[$i]->normal : ''; ?>"/> <!-- Line B -->
<input type="text" name="wrap<?php echo $i; ?>"
value="<?php echo isset($diagram->files[$i]) ? $diagram->files[$i]->wrap : ''; ?>"/> <!-- Line C -->
</fieldset>
<?php
}
?>
<div class="submit">
<input type="submit" value="Save"/> <!-- Line D -->
<input type="reset"/>
</div>
</form>
</body>
</html>
def.php
class SapDiagram
{
public $files;
public function goAhead(&$file, $index = null)
{
if (is_null($index)) {
$index = sizeof($this->files);
}
$this->files[$index] = $file;
}
}
Problem Statement:
I am wondering what changes I need to make at Line A
and or inside the goAhead
method in order to avoid this error.
Note: goAhead() method is being used at many places in the code so I believe removing &
is not the solution.
2
Answers
See the manual: …no other expressions should be passed by reference, as the result is undefined. For example, the following examples of passing by reference are invalid:
https://www.php.net/manual/en/language.references.pass.php
When you define your function as
goAhead(&$file, ...)
, that&
is a Pass By Reference, which is not compatible with something likegoAhead(1, ...)
orgoAhead(new ..., ...)
, etc.To solve this, read your error and pass a variable.
Instead of
Define a variable and use that:
So all in all: