I am trying to fetch some variables into another file from a PHP class and could not quiet figure out the way to do it.
I am attaching a piece of dummy code which shows what exactly I am trying to do
Suppose there is a PHP class named Products.php in which there is a function getProducts() which have a variable $product_name
public function getProducts() {
$product_name = "Some name";
}
Now I want this variable $product_name to be used in a seperate file which is named as products.php. How can i use it there? I made an instance of the class like
$products = new Products($connection);
The above is just an example so please don't mind any other mistakes made, I just want to know how can i access that variable into another file!
Thanks for all the helps in advance.
You need to use return
in the function and include the PHP file with the function in your file. The result looks somewhat like this:
file1.php
public function getProducts() {
$product_name = "Some name";
return $product_name;
}
file2.php
include 'file1.php';
$product_name = getProducts();
Please keep in mind that PHP code written in this way is bad style. Here are some explanations on how PHP should be written: https://www.phptherightway.com/