Suppose I have the following code:
a.php
<?
class H{
public $i = 123;
public function S(){
require "b.php";
die;
}
}
$i = new H();
$i -> S();
b.php
<?
echo $i->i;
However, system throws an error in file b.php that variable i is not defined.
How can I fix this problem?
If it's possible, could someone kindly tell me why this is happening?
You should never include a file like that in case of OOP. As oop and procedural PHP is different. Whenever you want to echo anything inside the class you should use $this keyword that signifies that you are working in context of current class object. So thats why your code is not working and you are getting that variable i is not defined. As nathanael said its not an elegant way of coding
you can write in b.php
echo $this->i;
and that would work, but that is not an elegant way of coding,
alternatively you can make$i
accessible inS()
ina.php
you would have
public function S(){
global $i;
require "b.php";
die;
}
And that would work also, but is no more elegant
when you requireb.php
in the methodS()
, it will inject the code fromb.php
inside the methodS()
, and there is no variable$i
you have a global variable$i
, which is not accessible fromS()
unless you explicitly make it accessible
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Find the answer in similar questions on our website.
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.
PHP (from the English Hypertext Preprocessor - hypertext preprocessor) is a scripting programming language for developing web applications. Supported by most hosting providers, it is one of the most popular tools for creating dynamic websites.
The PHP scripting language has gained wide popularity due to its processing speed, simplicity, cross-platform, functionality and distribution of source codes under its own license.
https://www.php.net/
Welcome to the Q&A site for web developers. Here you can ask a question about the problem you are facing and get answers from other experts. We have created a user-friendly interface so that you can quickly and free of charge ask a question about a web programming problem. We also invite other experts to join our community and help other members who ask questions. In addition, you can use our search for questions with a solution.
Ask about the real problem you are facing. Describe in detail what you are doing and what you want to achieve.
Our goal is to create a strong community in which everyone will support each other. If you find a question and know the answer to it, help others with your knowledge.