2

In ProjectsController.php I'm setting a session variable as I'd like that info to be accessible in ALL controllers, models and views:

$this->Session->write('Project.title', $this->Project->title);

Now, when I try access it from Projects view, like this:

        <p>Project: <strong>
        <?php if (isset($session->read('Project.title'))): 
            $session->read('Project.title');
        ?>
        <?php else: ?>
            Not selected
        <?php endif; ?>
        </strong></p>       

I'm getting the following error:

Fatal error: Can't use method return value in write context 

Which refers to the second line of above code.

I've been through CakePHP documentation and also searched SO, what am I doing wrong here?

Thanks!

EDIT:

I've also tried using:

$this->Session->read('Project.title')

resulting in the same error message.

2 Answers 2

6

You should do what PHP tells you once in a while :) The error message is pretty clear. You cannot use isset() and empty() this way. They only work with variables direcly, not methods. So use

<?php if ($this->Session->check('Project.title')) {
    echo $this->Session->read('Project.title');
} ?>

as documented in the cookbook

you could also do

<?php
$title = $this->Session->read('Project.title');
if ($title) {
    echo $title;
} ?>

or even

<?php if ($title = $this->Session->read('Project.title')) {
    echo $title;
} ?>

the last one is not cakephp coding convention, though.

Sign up to request clarification or add additional context in comments.

2 Comments

Yes Mark, I should definitely listen to it:) This resolved it, thanks.
For a CakePHP 3.x solution refer to stackoverflow.com/a/32668870
0

isset() cannot deal with functions like that. Store the return value of that $session object's read() function, then test that variable inside the if() condition:

$title = $session->read('Project.title');
echo ($title) ? $title : '';

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.