php class constructor - php

Hi I have a class as follows:
<?php
include '(OrderContainer.php)';
class OrderAuthenticator
{
private $OrderObj;
public function __construct($Order)
{
$this->OrderObj = $Order;
echo 'Created an instance os OrderContainer<br/>';
}
//Misc methods.....
}
?>
Then I have a method that tries to instantiate this object
<?php
include ('OrderAuthenticator.php');
$Authenticator = new OrderAuthenticator($OrderObj);
?>
Problem is that in the object is not instantiated.....
No matter what I do ..... Im new to PHP so I was wondering if there is something quite obvious here that Im not doing?
Could someone please give me a hand..
Thanks

It seems as include '(OrderContainer.php)'; should be include('OrderContainer.php'); instead.
Make sure $OrderObj is defined in the main script creating an instance of OrderAuthenticator.
To debug, be sure that PHP is showing error messages by starting with error_reporting(E_ALL); ini_set('display_errors',1); first in the main script.
Also, make sure you have no syntax error (for example, by printing "Hello world" in your script).

You need to create an $OrderObj to be passed in to the constructor

Just remove public from constructor.

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 Basics Create Object

<?php
$myClass = new MyClass;
$myClass->myFunc();
class MyClass
{
public static function myFunc() {
echo 'testcall';
}
}
?>
Does php go from top to bottom?
If so why does php know MyClass at the moment where I create an instance of it?
There is no need of forward declaration in PHP, instead you need to have the class declared in current script even if it's after the object invocation. but for any included script include statement needs to be executed before you create instance of that class.
That's why your code works.
In PHP there is no need of declaration previously, You can use it at the time of using it that variable.Your code is working as you included it in the same file
At the time of declaring class in another .php file you have to include it compulsory before initiating the object of that particular class.
Hope it is useful to you :)

How can I get php class methods in AJAX Call?

I am creating a mobile app with Phonegap. Because the project is server-based, I use JQuery and AJAX to connect to php files lying on a server. Now I am having the following problem:
I make a AJAX call to, say, the php file login.php by
$.post('http://example.com/php/login.php',
{
}).success(
function(data){
console.log(data);
}).error(
function(data){
//return error
console.log("Error post ajax " );
},'json');
In login.php I want to use class methods, where the class is written in another php file, class.php.
So login.php looks like this
<?php
require_once('http://example.com/php/class.php');
$test = $class->test();
echo json_encode($test);
?>
and class.php looks like this:
<?php
class CLASS {
public function test(){
echo "test";
}
}
$class = new CLASS;
?>
But I can not use the method test() in the class CLASS. If I write the CLASS in the login.php file, of course it works, but this is not what I want.
Has anyone some tipps for me how to tackle this problem?
You should be instantiating the class in login.php by convention.
This:
$test = $class->test();
Should be this:
$test = new CLASS();
$test->test();
I think you said this is not what you want, so this might fix your issue:
You are not declaring the $class variable correctly:
This:
$class = new CLASS;
Should be this:
$class = new CLASS();
You need to learn a few basics, for example from this tutorial http://tut.php-quake.net/de/, and get some things straight. Many things you do are plain wrong
require_once('http://example.com/php/class.php');
you do not include like that, you include the raw path on your server, not an URL
require_once('/path/to/your/file/class.php');
More like this.
$test = $class->test();
this also will not work when your function looks like
public function test(){
echo "test";
}
this, your function has to return the value
public function test(){
return "test";
}
to achieve what you try.... consider getting some basics straight first would be my first advice, keep in mind I just want to help you because you will struggle more often if you don't get those basics and know the language you are using ;)

Fatal error: Class 'Logs' not found in

I'm going crazy over these past few days and I really need your help because I don't know what else to do. I tried everything.
Here is the problem:
I have two files. site.php and logs.php.
Here is the content of logs.php:
class Logs {
function __construct() {
}
}
Now comes the fun part, beginning of 'site.php':
require_once("database.php");
require_once("logs.php");
class Site {
private $db;
private $logs;
function __construct() {
$this->logs = new Logs(); ### this is the error line
$this->db = new MySQLDatabase();
}
}
They are all in the same directory. Why can't it find my class?
PHP might be including the wrong the file. PHP will search the include path before looking inside the script's directory. You may somehow have a logs.php in your include path (See This PHP manual for details.) I suggest maybe adding an echo "hello world"; in the root of your logs.php.
You might also have accidentally enclosed the class inside another class or function. Make sure the class is only inside the tags.
Thank you all for helping. I have found out what the problem was! Turns out, for some reason I shouldn't name my php file 'logs.php'. As soon as I renamed it, it works perfectly. I have no idea why but it just wont work with that name.

Avoiding Multiple Class Instantiations of Single Class PHP?

I've got a class I wrote to work with the front end (web browser side) of a shopping cart.
It's fairly simple in that I send the class a product ID that I bury in the URL and then query a database populating the classes variables for use in retrieving the data through some public methods.
To interface with my actual physical web page I have a file I call viewFunctions.php. Wherein I instantiate my class called ItemViewPackage():
<?php
require_once(dirname(__FILE__) . '/ItemViewPackage.php');
$viewObject = new ItemViewPackage($_GET['page']);
So, I have shoppingcartpage.php (the physical url) that requires the file viewFunctions.php that loads my class ItemViewPackage().
The output page shoppingcartpage.php calls functions like get_item_info('title') or get_item_info('price') which in the viewFunctions.php file is made like so:
function get_info($type){
echo $viewObject->get_info($type);
}
Now, right off the bat, this isn't working because, I assume, $viewObject is not global. So I make $viewObject global like so:
function get_info($type){
global $viewObject;
echo $viewObject->get_info($type);
}
But, this doesn't work either, I still get an error for "Call to a member function get_info() on a non-object"
Now, the only thing that works is:
function get_info($type){
$viewObject = new ItemViewPackage($_GET['page']);
echo $viewObject->get_info($type);
}
But, I don't want to re-instantiate my object every time I make a call to this function (which is several times for several bits of information). I'd rather instantiate once at the top of my viewFunctions.php doc and use that object every time I call this function.
Am I going about this completely wrong?
Thanks in advance.
DIAGRAM (hopefully it helps visualize)
What for do you need viewFunctions.php anyway? It's only wrapping the ItemViewPackage. Remove that and use the ItemViewPackage directly, e.g.
// shopping.php
include_once 'ItemViewPackage.php';
$viewObject = new ItemViewPackage($_GET['page']);
<div><?php echo $viewObject->get_info('title'); ?></div>
<div><?php echo $viewObject->get_info('price'); ?></div>
Then you dont have to bother with globals or Singletons. If you dont want a second instance, dont instantiate a second one. It's simple as that in PHP. If there is anything in viewFunctions.php that modifies the output of the $viewObject instance, consider making that into a class and have it aggregate the $viewObject into a property, e.g.
// viewFunctions.php
include_once 'ItemViewPackage.php';
$viewObject = new ItemViewPackage($_GET['page']);
$helper = new ViewObjectHelper($viewObject);
then you can access the $viewObject from within the Helper object with $this->propertyName.
As for reducing load to the database: this is a solved problem. Consider using a cache.
You want the singleton pattern, please see this answer:
Creating the Singleton design pattern in PHP5
This allows you to get an instance of your class in any scope, and it will also be the same instance.
What scope is the $viewObject created in?
Note: that even though it appears to be in the global scope because it is not in a function within the shown file, if the file is included from within a function it will be in that scope...
i.e.
file1.php
include 'file2.php';
function includefile($file) {
include $file;
}
includefile('file3.php');
file2.php
$global = 'this is global';
file3.php
$notglobal = 'this is not';
<?php
require_once(dirname(__FILE__) . '/ItemViewPackage.php');
$viewObject = new ItemViewPackage($_GET['page']);
function get_info($type){
global $viewObject;
echo $viewObject->get_info($type);
}
This should work from viewFunctions.php and any file that includes it such as shopping.php. So from shopping.php we can do either:
echo get_info($type);
or
echo $viewObject->get_info($type)
This alone raises some logical flags in my head. Not sure why you want to wrap the object again.

Categories