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.
Related
Following non OOP file (incOverview.php) :
<?php
echo show_value();
classView.php
<?php
class myView
{
public function loadView()
{
include("incOverview.php");
}
public function show_value()
{
return 42;
}
}
$objView = new myView();
$objView->loadView();
This will not work, it's only a sample to explain my problem.
I expect "12"
When i include this file in an PHP class, the global function show_value does not exists, as expected.
But it exists inside the class. Normally the included file must be changed to $this->show_value(); but in this scenario it is not possible.
Is there a solution, to include this non OOP file into my class and the class handles all requested functions ?
You can wrap functions in your non-oop file as a trait and include trait inside your classes. Or include your file outside the classes. And functions will be available in global namespace.
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'];
}
}
I get a parse error when trying to use a name space inside my own function
require('/var/load.php');
function go(){
use test\Class;
$go = 'ok';
return $go;
}
echo go();
From Scoping rules for importing
The use keyword must be declared in the outermost scope of a file (the
global scope) or inside namespace declarations. This is because the
importing is done at compile time and not runtime, so it cannot be
block scoped
So you should put like this, use should specified at the global level
require('/var/load.php');
use test\Class;
function go(){
$go = 'ok';
return $go;
}
echo go();
Check the example 5 in the below manual
Please refer to its manual at http://php.net/manual/en/language.namespaces.importing.php
From the manual:
The use keyword must be declared in the outermost scope of a file (the global scope) or inside namespace declarations.
From what I gather a lot of people are getting this when including a separate function file and trying to use the static method inside that function.. For example in index.php
namespace foo/bar
require('func.php')
f();
and in func.php
function f() {
StaticClass::static_method();
}
you simply need to declare namespace foo/bar in func.php (same like how you declared it in index.php) so instead of the above it should look like:
namespace foo\bar
function f() {
StaticClass::static_method();
}
to avoid errors like:
Fatal error: Uncaught Error: Class 'StaticClass' not found in func.php
It's obvious now but I was confused why func.php does not carry over the namespace declaration inside the file that 'requires' func.php
in C , i can define a function to be static so it can only be used in it's own file.
in python , i can define a function with it's name starts with _ so this function can't be used outside this finle.
could i do it in php ?
If you really mean "functions": No, both arent possible.
First: Functions are always static.
Second: In PHP namespaces are not bound to a file. So a file can declare non, one or more namespaces. On the other side a namespace can be declared in different files. Its difficult to define a consistent way on how non-public functions can get resolved. You can use static classes instead.
A class can be used to for data hiding and implementing encapsulation.
You can use private keyword to declare functions in php to hide them outside of code but the all are bounded with class.
Only class can use these type of functions.
class A
{
/* This method will only be accessible in this
class only by the other methods of this class
and will be hide from rest of program code*/
private function setValues()
{
//some stuff
}
public function getVal()
{
$this->setValues();
}
}
The method above can only be accessible by this class.
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.