1

In Joomla 3:

I'm writing a class to represent a semi-complex data structure. In that class, some methods need to access the app, dbo, document and user objects from JFactory.

Here's a snippet of the code:

class Survey {
    use Joomla\CMS\Factory;
    
    private $app = JFactory::getApplication();
    private $doc = JFactory::getDocument();
    private $db = JFactory::getDbo();

I'm getting an error on the line private $app = JFactory::getApplication();, the error is:

Fatal error: Constant expression contains invalid operations in /joomla path/media/tmpl/classSurvey.php on line 46

I've also tried to set it up inside the constructor, but I get the same error message:

function __construct($surveyID = -1) {
    $this->app = JFactory::getApplication();
    $this->doc = JFactory::getDocument();
    $this->db = JFactory::getDbo();

Do I need to get these objects outside the class and pass them via the constructor?

Forgive me if this is the wrong place to ask this, but it seemed to be the only Stack Exchange site related to Joomla I could find.

Thanks!

1
  • Your Joomla-related questions are 100% welcome here. Thanks Sloan.
    – mickmackusa
    Feb 22 at 1:38

2 Answers 2

2

The USE statement should be before the Class statement, or outside the Class.

use Joomla\CMS\Factory;
...
class Survey {

These lines

private $app = JFactory::getApplication();
private $doc = JFactory::getDocument();
private $db = JFactory::getDbo();

are in the right place inside your class however they should be

private $app;
private $doc;
private $db;

and then your _constructor looks okay but JFactory is now Factory.

function __construct($surveyID = -1) {
    $this->app = Factory::getApplication();
    $this->doc = Factory::getDocument();
    $this->db = Factory::getDbo();

Having $app, $doc and $db as Private may cause conflicts with other code and so generally you see them as Public and not Private. Given your code appears to be in a template you may find they are already available to you and don't need to be created in the constructor.

3

It's worth noting that "Constant expression contains invalid operations" is thrown if you ever try to set a class property using a variable. Class properties declarations are set at compile time prior to variables having values in memory. Hence you have to populate the values within the constructor.

class Survey {

    private $app = JFactory::getApplication(); // this is a fatal error
    private $resolved_prior_to_variables_having_values = 1; // this is fine

    // ... etc
1
  • Thanks for the answer! I had a lot of trouble deciding which answer to check mark. Your answer and the one by Irata together solved my problem. Thanks! Feb 24 at 19:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.