DrewInPB
DrewInPB

Reputation: 11

PHP and Smarty Error: Trying to get property of non-object

I am new to both this site and learning PHP. I am using the text Beginning PHP5 and MySQL E-Commerce From Novice to Professional by Darie and Bucica to create an e-commerce website. I believe some of the errors I have encountered so far were due to the updated database (MDB2). I have been able to get past every error except this one. The code is supposed to pull the list of departments from my database using Smarty.

I get the error "Trying to get property of non-object" on the last line. I have a feeling it has to do with the is_array() function.

<?php $_smarty_tpl->tpl_vars["load_departments_list"] = new Smarty_variable("departments_list", null, null);?>
    <table border="0" cellpadding="0" cellspacing="1" width="200">
     <tr>
      <td class="DepartmentListHead"> Choose a Sport </td>
     </tr>
     <tr>
      <td class="DepartmentListContent">
       <?php unset($_smarty_tpl->tpl_vars['smarty']->value['section']['i']);
    $_smarty_tpl->tpl_vars['smarty']->value['section']['i']['name'] = 'i';
    $_smarty_tpl->tpl_vars['smarty']->value['section']['i']['loop'] = is_array($_loop=$_smarty_tpl->getVariable('departments_list')->value->mDepartments) ? count($_loop) : max(0, (int)$_loop); unset($_loop);

If there is anything else you need to help answer please let me know! Please be as descriptive as possible and show the solution using my code if possible. Thanks for your help! -Drew

Upvotes: 1

Views: 3833

Answers (2)

usoban
usoban

Reputation: 5478

Try checking each variable for type using var_dump():

var_dump($_smarty_tpl->getVariable('departments_list'), $_smarty_tpl->getVariable('departments_list'))->value,
$_smarty_tpl->getVariable('departments_list'))->value->mDepartments);

That will tell you what type values are. The problem doesn't really lie in is_array function, but in the fact, that with $_smarty_tpl->getVariable('departments_list'))->value->mDepartments you are trying to access object property in two cases, on returned value of getVariable() method, and getVariable()->value, so one of those two is doing you trouble.

Upvotes: 0

German Rumm
German Rumm

Reputation: 5832

Your are using $_smarty_tpl->getVariable('departments_list')->value->mDepartments inside your in_array function. Make sure that you assigned departments_list to a smarty object.

OR add a check before that

$departments_list = $_smarty_tpl->getVariable('departments_list');
if (is_object($departments_list) && is_object($departments_list->value)
         &&  $departments_list->value->mDepartments) {
    $_smarty_tpl->tpl_vars['smarty']->value['section']['i']['loop'] = is_array($_loop=$_smarty_tpl->getVariable('departments_list')->value->mDepartments) ? count($_loop) : max(0, (int)$_loop); unset($_loop);
}

Upvotes: 4

Related Questions