Calling function in PHP class not working - php

I have a a class stored in path plug/PHPDocumentParser/DocumentParser.php:
namespace LukeMadhanga;
class DocumentParser {
static function parseFromString($string) {
// do stuff
}
}
I want to call the class and function. I run this in a file that's stored at the base folder:
include_once("plug/PHPDocumentParser/DocumentParser.php");
$docObj = new DocumentParser();
$docText = $docObj->parseFromString('hello world');
I receive this error:
Fatal error: Class 'DocumentParser' not found
I am pretty sure the problem is how I call the class, correct?

You are calling static function in wrong way. Try
DocumentParser::parseFromString()
Also use require_once, you will know if it was included correctly. (maybe path is wrong.)
Edit : Ok, you added namespace now - it should be \LukeMadhanga\DocumentParser::parseFromString() thats also why you dont get instance of DocumentParser using new.
Of course you can always add use keyword at top of your file to include your namespace.

Related

PHP class includes a file, but that file cannot access the class

I have a php class that uses "include" to load some html and php from a file. Within that file I want to access the class object that included the file, but I keep getting "Fatal error: Call to a member function makeSizesSelect() on a non-object ..."
I've tried both include and require, I've tried declaring globals, I've tried everything I can think of and everything I've so far found on SO. Nothing seems to allow the file I include to have php code access the object that included it.
Any ideas?
Here's a few snippets ...
The class file:
class cdf {
public $version = 001;
public function cdf_shortcode( $atts,$content )
{
$this->slog( 2,"shortcode() case: show" );
require( 'templates/container.php' );
}
}
And the required file container.php contains the following (amongst other stuff):
<?php
echo "version = ".$this->version;
?>
I then try to use the object:
$cdf = new cdf();
$cdf->cdf_shortcode( null, null);
The line $this->slog( 2,"shortcode() case: show" ) works. It runs that function (which I haven't included in this snippet) just fine. But then the file I require (or include) cannot use $this to access the object. I'm at a loss. :-(
All I want to do is access within the included file, the variables and methods in the class that included the file ...
Sorry, some added information. I'm not sure if this makes any difference. The code above is all part of a WordPress plugin.
Curious issue with a curious solution. I finally found the answer over here:
Possible to access $this from include()'d file in PHP class?
I tried all the obvious solutions this poster tried (globals, casting to another variable, etc) with the same lack of success. Turns out, just changing the file extension from .php to .tmpl fixed the issue, and my included file can now access the object that included it. Weird. (Of course, the downside now is that my IDE doesn't colour my code for me. :-( )
Thanks for your suggestions guys.
In the file you included you need to instantiate the class.
<?php
$yourClass = new cdf();
echo "version = ".$yourClass->version;
?>
When you want to access a function in a class, you need to instantiate the class first otherwise you wont have access to anything inside of it.
Also make sure the file you are including wont be included anywhere else where the class cdf doesn't exist because that will result in an error.
The variable $this can only access methods, variables, etc. only if they are in the same object.
Update based on your answer that seems to have worked:
Example.php
<?php
echo $this->returnString();
echo $this->randomVariable;
File.php
<?php
class IncludedClass
{
public $randomVariable = 123;
public function returnString()
{
return "some random string";
}
public function meh()
{
require_once('Example.php');
}
}
$meh = new IncludedClass();
$meh->meh();

PHP: Understanding the include scope with spl_autoload_register

I'm trying to autoload Classes, but I'm hindered by the scope. The Class is being loaded, but I'm using it out of scope. Here's the code to further explain what I'm trying to do.
AutoLoader.php
<?php
class AutoLoader {
private $namespace;
public function __construct($namespace) {
$this->namespace = $namespace;
spl_autoload_register(array($this, 'ClassLoader'));
}
private function ClassLoader($class) {
$class = "classes/{$this->namespace}/{$class}.php";
print("Loading class: {$class}");
include "{$class}";
}
}
?>
script.php
<?php
ini_set("display_errors", 1);
$loader = new AutoLoader("myspace");
$MyClassObj = new MyClass();
$result = $MyClassObj->MyClassFun();
?>
So when it comes down to script.php, I get the print out that it's loading the class and I don't get any errors that it can't find the file. So it looks like it's loading, but when I use the class to create a new object, it tells me it can't find the class. So I'm loading the include out of scope.
I included the AutoLoader in a separate file so I could load it into multiple files. Am I able to make this work or must the AutoLoader be part of script.php instead of separate?
edit: Including error, added error display to script.php.
Loading class: classes/myspace/MyClass.php
Fatal error: Class 'MyClass' not found in /usr/local/apache2/htdocs/scripts/script.php on line 5
edit: Including MyClass.php and directory structure
MyClass.php
<?php
class MyClass {
public function MyClassFun() {
$var = "hello world";
return $var;
}
}
?>
Directory Structure
htdocs/scripts/script.php
htdocs/classes/myspace/MyClass.php
htdocs/AutoLoader.php
If I change the class to MyClasse (misspelled) it will error on the include because it can't find the file. So using the proper MyClass I can only assume that it's finding the file since it's not producing an error. So the include looks good, but it still won't use it.
Which, now that I think about it more, is strange. The include is only occuring because of line 5 when I go to use the class. ClassLoader is being called by the spl_auto_register to search for the class. It's finding and including the class. Yet the same line 5 fails to actually use it.
I guess I don't understand that disconnect. Line 5 is properly calling the ClassLoader, but then fails to actually find the class once loaded.

PHP - Is this good require_once or extends

I'm a newbie in php but I'll try to get straight to the point.
I have a class called ConnectionManager
class ConnectionManager
{
function ConnectToDB()
{
//PDO connection code
}
}
and in my other manager InstitutManager I am using require_once($filename) to get access to my ConnectionManager functions
require_once('../manager/ConnectionManager.php');
class InstitutManager
{
protected $connInstance;
function _construct()
{
$this->connInstance = new ConnectionManager;
}
function getInstituts()
{
$conn = $connManager->ConnectToDb();
//retrieve instituts
}
}
The question is : Should I be using extends ConnectionManager in my InstitutManager instead of require_once? Why should I use one more than the other?
Thanks
Edit : Changed code for InstitutManager class
Would this be ok like this? Or should I pass a pass a parameter with my connection already instanciated in function _construct($conn)?
Your include_once reads in a source file, which in this case has a class definition for ConnectionManager in it. Your extends sets up class InstitutManager as inheriting class ConnectionManager, i.e. InstitutManager gets everything in ConnectionManager and can then define its own modifications to that basic structure. There isn't really any relationship at all between the two operations, and your $connManager = new ConnectionManager operations are nonsensical.
require_once 'file'.php' just means that the PHP interpreter will take the contents of a file called file.php and dump it right there in the spot where the include was called. Kind of like what would happen if you would select everything in a Word file, click copy and paste it at the top of another Word file.
In your case you need to include the file, or else it will not know where to find the ConnectionManager class.

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 Method Disappears?

I am including one PHP script into another using PHP's require_once() method. This script contains a class, TemplateAdmin, which instantiates itself right after the script, like this:
class TemplateAdmin {
// Class body...
}
$templateAdmin = new TemplateAdmin();
This was working fine for a while. However, I have adopted a new importing technique to include classes and packages. I have tested this new technique, and it works! However, for some strange reason, none of the methods in any of the classes I import are there when I need them. However, it seems as though the instance variables are still there.
For example, when a class with this absolute path is called:
require_once("C:\wamp\www\wave_audio\system\server\templates\TemplateAdmin.php");
... I get this error in the call stack:
Fatal error: Call to undefined method stdClass::top() in C:\wamp\www\wave_audio\cms\index.php on line 189
This error is referring to my use of the top() method inside of the TemplateAdmin class.
Does any one have any idea as to why this is happening??? If this helps, I have been using require_once() all along, I am running PHP 5.3.5 on a Windows XP Media Center machine.
Thank you for your time!
Assuming you dont want to use globals here is one way that only requires a few changes.
TemplateAdmin.php:
class TemplateAdmin {
// Class body...
}
return new TemplateAdmin();
Return include once in import:
function import($classes) {
//Convert ECMAScript style directory structures to Unix style
$address = str_replace(".", "/", $classes);
$address = INSTALL_ROOT . "system/server/" . $address . ".php";
if (file_exists($address) && is_file($address)) {
return require_once($address);
} else {
die(""" . $classes . "" does not link to an existing class");
}
}
Assign the variable:
$adminTemplate = import('templates.TemplateAdmin');
I have a feeling your php error message is accurate. I know on your stripped down version, you pieced it together how you're sure it's setup but it's obviously not a direct copy/paste since it's like:
class TemplateAdmin {
public function top() {
//The "top" method...
}
}
So, the error message says that the method "top" is not defined. If it were not including your file properly, it would tell you that the class you instantiated doesn't exist. Either that method does not exist in the class you think it is, or the method has been unset somewhere in that object instance. Trust your error message.

Categories