PHP class unable to access included variables - php

This is a PHP newbie question:
I want to give my class access to my database credentials in an include file: ../config.inc
<?php
$db_info['host']='localhost'; // and so forth
...
?>
Later, in my class source file I have:
<?php
require_once('../config.inc'); // include the above file
public class Foo {
static function Host() {
echo $db_info['host'];
}
}
?>
When try to access the class in other code, I get an error claiming that $db_info is undefined. When I try to move the require_once inside the class scope (after Foo {) I get a syntax error, so apparently one can't use require_once inside the class. What are the best practices when writing class static methods that need access to included data? THANKS.

You have a issue with the scope. Your included variable is available outside your class but not inside your class. The suggested methods should be to pass the variable to the constructor of your class and store it in a member variable of the class.
But since your using the function as static then you can use global but its not best practices to do so. alternatively you can include the file with in the function.
public class Foo {
static function Host() {
require_once('../config.inc'); // include the above fil
echo $db_info['host'];
}
}

Related

500 Unable to handle this request

Inside a method in my Model class, I include another PHP file. The code works until that included PHP file declares a class definition ie class Test123 {}.
The class name is unique. The only possible source of the issue that I could think of would be how I'm including a class within a class. However, I wasn't able to find information about this, so I assume it isn't a problem.
Any ideas?
//Inside of method inside of model class
include "{$_SERVER['DOCUMENT_ROOT']}/models/language.php";
I believe you're right in assuming that you can't declare a class inside a class, which is what you're essentially doing by including it inside a class method.
Could you perhaps do something like this?
class.php:
<?php
include("otherclass.php");
class MyClass {
public function run () {
$otherClass = new OtherClass();
}
}
otherclass.php:
<?php
class OtherClass {
}
index.php:
<?php
include("class.php");
$myClass = new MyClass();
$myClass->run();

Classes - require conflict in constructor

I'm coding a Wordpress plugin and I'm not sure regarding the function name conflict..
I have a file named test_handling.php which contains the following content :
function testing() { echo 'test'; }
I included this file in a class constructor (file named testcls.class.php) :
class TestCls {
function __construct() {
require_once('test_handling.php');
testing();
}
function otherfunction() {
testing();
}
// ...
}
In this case, I would like to know if the testing() function is only available in the TestCls class, or can it create conflicts if an other WP plugin has a function with the same name ?
Even with the same name, the functions will have different scope if defined as class method. To make a call to a regular function you will do the following:
testing();
and the result will be:
'test'
the class method need an instance of the class or be statically called. To call the method class you will need the following formats:
$class->test();
or
OtherPlugin::test();
To sum up, the function test will be different if defined as class method. Then, you will not have conflicts.
Other way to encapsulate your function and make sure you are using the right one is with namespaces. If you use a namespace in your test_handling.php
<?php
namespace myname;
function testing(){echo 'test';}
?>
You will access the function test like this:
<?php
require_once "test_handling.php";
use myname;
echo myname\testing();
Now you are sure about the function you are calling.
When a file is included, the code it contains inherits the variable
scope of the line on which the include occurs. Any variables available
at that line in the calling file will be available within the called
file, from that point forward. However, all functions and classes
defined in the included file have the global scope.
from include in PHP manual
Which means that yes, you can have conflicts.

PHP class inherit variables in included file

I have like:
class Class2 extends Class1 {
.....
function __construct() {
parent::__construct();
$var_in_included_file;
}
}
class Class1 {
function __construct() {
include_once('my_file.php')
}
.....
}
my_file.php:
$var_in_included_file=10;
The problem is that I cannot receive value of $var_in_included_file. Is there a way to receive this value without add many codice like:
$this->var=$var_in_included_file ....?
Because I have many thousands of variables.
Thanks.
More abstract the problem is:
in some file I received (from $_POST) near 500 variable.
These variables have be elaborated in complicated way. For simplify this elaborating I need create tree of class inheritans - but in this case these variables will not seen in child classes without assigning them to class variables - but this produses enormous volume of code.
In class one, assign your variables to class variables:
class Class1{
private $someVariable;
public function __construct(){
include_once 'my_file.php';
// variable declared in my_file.php
$this->someVariable = $someVariable;
}
}
Now that variable is accessible in child class, through $this->someVariable.
Happy coding, good-luck
As explained in include() and variable scopes, when you include a file in your __construct() method, the scope of the variables in the file you're including is limited to the __construct() method, not the class.
Your options would be to either change the content of the included file to include a $this-> in front of the variable name (i.e. $this->var_in_included_file = 10;) or add a $this->var_in_included_file = $var_in_included_file; in your __construct() method.
Class1 {
include_once('my_file.php')
.....
}
Is not possible

What to use istead of THIS in php OOP?

I have a static class that loads additional php file inside of one of its function and I need to access class variables from this file withous knowing the class name.
But This::SomeVar - doesn't work.
But I know there's another way to do it, I just can't find anything about it.
So here's the example class
class SomeClass {
static function Initialize() {
require_once 'somefile.php';
}
}
and inside that file I need to access static variable something like this
This::SomeVar= 'qwe';
Use self::$SomeVar to access static class members.
$this->someVar for fields and self::$someVar for statics
You can use $this->someVar to access a property from inside a class.

How can I initiate a PHP class and use it in several files?

I am stumped right now. In my last post about this question the answer was to use a singleton to make sure an object is only initiated 1 time but I am having the opposite problem.
If I have a file called index.php and then I include these files into it, class1.php, class2.php, class3.php, class4.php.
In index.php I will have,
<?PHP
$session = new Session();
require_once '/includes/class1php';
require_once '/includes/class2.php';
require_once '/includes/class3.php';
require_once '/includes/class4.php';
?>
then in all 4 of the test files I will try to access a method called get() from the session class, assume the session class file is already included into the index.php page as well.
Now if I try to use...
$testvar = $session->get($var1);
in any of the test class files I will get this error
Fatal error: Call to a member function get() on a non-object
the only way the code works without an error is if I use
$session = new Session();
in every file.
How can I fix/avoid having to initaite the class in every file when it is already initated in the index.php file?
the goal is to let me initiate a class in 1 file like index.php and then include the class files into that page, the catch is most of the classes use methods from other classes so would be nice if I didn't have to initiate every class in every file
Without seeing the code it's hard to tell, but I think I can make some assumptions. correct me if I'm wrong:
EDIT: So post your source so we can stop speculating
1) The files you are including are class files. in other words, they contain something like:
class a
{
function a(){}
function b()
{
}
}
2) You aren't trying to execute code in the class files, at load time, but at some later time by instantiating them
i.e.
require("class.a.php");
$myA = new a();
$a->b();
If you are trying to reference your session variable inside those classes, then you have a scope issue. A variable declared outside a class definition can't be used inside the class, unless it is declared as a global var inside the class.
class a
{
function a(){}
function willFail()
{
$session->doSomething(); //fails
}
function b()
{
global $session;
$session->doSomething(); //succeeds
}
}
Even then, you probably don't want to do that, but instead you should pass in your session as a variable if the class needs access to it:
class a
{
function a(){}
function b($session)
{
$session->doSomething(); // yay!
}
}
You could have a base class they all all extend from
Example
class test1 extends Base {
public function doSomething() {
$this->session->get('something');
}
}
class Base {
protected session;
public function __construct() {
$this->session = new Session();
}
}
You're kind of thinking about it backwards. Any file that will use the session object will need to include the file containing that class definition. The alternative is to use __autoload to pull the class in:
function __autoload($classname)
{
if ($classname == 'Session')
{
include_once 'Session.php';
}
}
EDIT : you'll need to put the file containing that autoload into every file that will use it.

Categories