Question:
class Productos{
var $nombre;
public function mostrarNombre(){
echo '<h3 class="product-name"><a href="#"><?= '$nombre' ?></a </h3>';
}
}
It tells me that the error in my code is:
syntax error, unexpected '$name' (T_VARIABLE), expecting ',' or ';'
But I do not understand why?.
Answer:
The error is because you are not correctly concatenating the $nombre
variable.
Solution:
You must use the dot ( .
) to concatenate.
echo '<h3 class="product-name"><a href="#">' . $nombre . '</a></h3>';
Classes and objects:
Once you solve the concatenation problem, you will run into another problem, and that is that you are not correctly referencing the $nombre
property of the Producto
class.
Also ( as @Learner points out ) it is not correct to use var $nombre
to define a property.
Solution:
-
Class properties must be defined as 'public', 'private' or 'protected' .
-
To access the properties of the class, you must use
$this
Example:
class Productos{
public $nombre = 'Nombre';
public function mostrarNombre(){
echo '<h3 class="product-name"><a href="#">' . $this->nombre . '</a></h3>';
}
}