Drupal 7中出现T_OBJECT_OPERATOR语法错误,求解决方案
Let's break down what's causing this error and how to fix it. That ParseError: syntax error, unexpected '->' might look like a pure syntax issue at first, but it’s almost always triggered because $job_node isn’t a valid object when your code runs—it could be undefined, null, or a non-object value like a string or array.
Here’s a step-by-step solution:
1. Validate $job_node exists and is an object
First, add a check to ensure we only attempt to access properties on a valid node object:
<?php // Confirm $job_node is a valid object before proceeding if (isset($job_node) && is_object($job_node)) { // Rest of your logic will live inside this block } ?>
2. Safely access the taxonomy term ID (tid)
Your original field access has two potential failure points:
- Hardcoding
'und'(undefined language) might not match your site’s language setup (use the node’s dynamic language key instead) - The field could be empty, so accessing
[0]['tid']directly will throw errors
Update your code to handle these cases:
<?php if (isset($job_node) && is_object($job_node)) { // Use the node's actual language key (falls back to 'und' if needed) $lang = isset($job_node->language) ? $job_node->language : 'und'; // Check if the field has a valid tid before proceeding if (isset($job_node->field_job_cv_destination[$lang][0]['tid'])) { $tid = $job_node->field_job_cv_destination[$lang][0]['tid']; $term = taxonomy_term_load($tid); // Ensure the term loaded successfully before accessing its name if ($term && is_object($term)) { $name = $term->name; // Add your logic to use $name here } } } ?>
3. Why this works
- The initial
$job_nodecheck prevents us from using->on an invalid value (the root cause of your syntax error) - Using
$job_node->languageinstead of'und'ensures compatibility with both monolingual and multilingual Drupal sites - Layered checks for array indexes and the loaded term eliminate undefined index errors and ensure we only access
$term->namewhen$termis valid
Bonus Best Practice
Whenever possible, avoid using PHP eval in Rules. Built-in Rules actions or custom Rules plugins are easier to debug, maintain, and more secure than eval’d code.
内容的提问来源于stack exchange,提问作者Viz

