I had a quick look around at some of the similar questions to mine, but none of the answers quite touched on the problem I am having.
I have two files. product.php and index.php. Product.php defines the product class, and I'm just using index.php as a page to output the variables. Ideally, this would be used to output objects from different classes in the future.
product.php
class Product{
public $var = "a default value";
public function __construct($var){
$var = $var;
}
public function displayVar(){
echo $this->var;
}
}
index.php (all enclosed in php tags obiously)
require_once("product.php");
$product = new Product();
echo $product->var;
I tried with different methods of including the file (require, include, include_once). I'm not sure if this is the issue.
The issue I'm getting is the $product->var doesn't output. Instead I get the following error:
Notice: Undefined property: Product::$var in C:\xampp\htdocs\FurnitureWebsite\index.php on line 21
I'm not entirely sure why it's considering this variable undefined. I looked through the PHP documentation on classes, and properties, but nothing that really looked like an answer.
A final note: I tried this with the class defined in index.php and it worked fine. This makes me think there might be something wrong with my file path, but the file name is spelt correctly, and the files are in the same directories, so I'm not totally sure.
$this->var = $var;change the value binddisplayVarto echo a public property. As it's public, you can access it directly. Or change the visibility of the property to protected or private if you want to restrict access to that property via an explicit getter.