undefined method despite method being defined - php

Having a very strange issue with an error on a codeigniter site.
Fatal error: Call to undefined method Document::get_by_module()
The line of code causing this (in a controller) is:
$this->document_type->get_by_module('module1');
The constructor of the controller:
function __construct(){
parent::__construct();
$this->load->model('document','document_type');
}
The document_type class looks like this
class Document_type extends CI_Model {
function Document_type () {
parent::__construct();
}
function get_by_module($prefix) {
// code
}
}
The main issue I'm seeing is that it's saying Document:: is the class, but it should be Document_type. I see no reason that it should be looking in the document class for that function.
If I remove loading of the 'document' class from the controller constructor, the error goes away (but other things break).
Not sure how something like that could be happening.

Looks like you are loading in the wrong model file. The line
$this->load->model('document','document_type');
means something along the lines of: Find me a model named "Document" create an instance and put under $this->document_type. (see the 4th example)
Looks like you have a Document model so the load succeeds, but if you don't want to rename your instance put under the $this (controller instance) you shouldn't use the second parameter in the $this->load->model() line.
Simply write $this->load->model('document_type');

Related

Calling function in PHP class not working

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.

Laravel View::share() does not work when testing

In my Laravel 4 project I've bound the current user to the views using the share() method like so:
View::share(['currentUser' => Sentry::getUser()]);
This works when browsing the site, all the views have access to the variable $currentUser. However, when attempting to test my application, the variable is never bound, despite a user definitely being logged in.
class PagesControllerTest extends TestCase
{
public function setUp()
{
parent::setUp();
// This works, as halting the application and dumping the user manually demonstrate it as such.
Sentry::login(User::first());
}
public function testIndex()
{
$this->get('/');
$this->assertResponseOk();
}
}
However, this simply results in a stack-trace of errors...
ErrorException: Trying to get property of non-object (View: ~/Sites/laravel/app/views/layouts/application.blade.php) (View: ~/Sites/laravel/app/views/layouts/application.blade.php)
...
Caused by
ErrorException: Trying to get property of non-object (View: ~/Sites/laravel/app/views/layouts/application.blade.php)
...
Caused by
ErrorException: Trying to get property of non-object
The exact line this fails at is where the view tries to access the $currentUser variable.
If I use a view composer instead, like follows, it solves the problem in this instance - but I want the variable available in ALL views, not just the ones I specify, and I'd also like to know WHY this is occurring.
View::composer('layouts.application', function($view)
{
$view->with('currentUser', Sentry::currentUser());
});
I'm guessing you are doing View::share in app/start/global.php. This file is invoked by calling parent::setUp(), which is before you've done Sentry::login, and thus, $currentUser will be null. You should either find a way to delay the View::share (using a view composer is one way to do this) or just use Sentry::getUser() in your views.

Using PHP function_exists in a class?

I am using OpenCart and installed the module sizes.xml, it edits the catalog/product/model/catalog/product.php file
It adds a class method;
I have an issue with some code where in a function I have:
class ModelCatalogProduct extends Model {
public function getSizes($product_id) {
...
} // end function
} // end class
We always get an error saying that we cannot redeclare getSizes method.
I want to either force redeclaration, or alternatively check whether the function exists before calling the method but I cannot use function_exists in a class.
ie, this seems illegal;
class ModelCatalogProduct extends Model {
// This throws up an error
if (function_exists('getSizes')==FALSE) {
public function getSizes($product_id) {
} // end function
}// end if
} // end class
It will throw up an error issue. But I need the function in there.
I would like to use function_exists in this class or alternatively force the method to be redeclared.
How would I make function_exists work inside a class?
You can't have executable code in a class that is outside of a method, so there's no way you can do what you're asking, as your if() condition would need to be in the class body.
So despite what others are saying, method_exists() is not a suitable answer to this question.
If you're getting an error stating that the method is already declared, then there are a few possible reasons for this:
It is actually already declared elsewhere in the same class. In which case, of course you can't redeclare it. But since the code for the class ought to all be in a single file, then it should be fairly easy to see that and avoid doing it.
It's declared in the parent class (ie in your case Model or one of its parents).
Under normal circumstances, you should be able to redeclare a method that is already declared in a parent class; your method would override the method of the same name from the parent class. So for most cases, your whole question is entirely unnecessary.
But you say you're getting errors, so clearly something is going wrong It would help if you'd told us the exact error message, but there are two reasons I can think of this might not work:
If the method in the parent class is declared as Final, then it means the author of the parent class explicitly doesn't want it to be overridden. This means that you cannot have your own method of the same name.
If the method in the parent class has a different signature - eg it's private in the parent but public in your class, or static in one but not in the other, then you will get errors complaining about that. In this case, you'll need to make sure that the methods have the same signature, or else give your method a different name.
Hope that helps.
The answer of #Spudley is correctly chosen as the right answer.
Just more explanation on the first case mentioned in the answer: if you wand to declare the function inside of a method of a class, you should also consider the namespace of the class:
class MyClass
{
function myFunction()
{
//here, check if the function is defined in the root namespace globally
// or in the current namespace:
if(!function_exists('someFunction')
&& !function_exists(__NAMESPACE__ . '\someFunction'))
{
function someFunction()
{
}
}
//....
someFunction();
}
}
If you don't check the second condition of if, calling myFunction() more than once would throw exception

Calling class method from other class (PHP)

I realize this is a common question and I have tried resolving it myself, but after following instructions from other answers I can't get it to work. So, this is the issue - I need to call a method from the class ClassOne in ClassTwo. So I did this:
class ClassOne{
public function methOne($par1,$par2){
mysql_query("insert into ps_loyalty_events (customer_id,event_id) values ('$par1','$par2') ") or die(mysql_error());
}
}
class ClassTwo{
private $customer; //initialize $customer in the constructor, to be defined as an instance of ClassOne() class and used as $this->customer
function __construct() {
$this->customer = new ClassOne();
}
public function methTwo(){
//some stuff here
$this->customer->methOne(6,10); //6,10 - randomly chosen parameters, irrelevant
//some more stuff here, this doesn't get executed at all
}
}
The priblem is not in ClassOne or the method methOne() because calling them directly from a regular PHP file in the following manner works:
$customer = new ClassOne();
$customer->methOne(6,10);
However, when I call it from the ClassTwo method, it does nothing - it just stops the execution of that function. Using try-catch doesn't seem to output anything. What am I doing wrong?
It's because your methTwo is static. When you call a static method of a class, that class is not instantiated into an object, and therefore it doesn't have the $this->customer property.
Unless there is a reason for the static method, you can change methoTwo:
public function methTwo(){
Edit: now that you have fixed that: what makes you think it isn't working? You don't do anything in methOne.
The code given is fine, see this Codepad demo of it working. That means there's some other code that we can't see that's causing the problem.
For simple solution, try to use extend classone in classtwo, so that all the method can user in classtwo by default
class class_two extends class_one
By above all the method of class one will be accessed into class two and can easily use that also. try it

Can php call non static method without instantiating the class first?

I register class methods for actions in my Wordpress plugin. When my method gets called by Wordpress, if I try to use the $this variable, php throws an error saying the call to $this variable is illegal outside the context of an object.
How can that be? I thought unless the method is static, you're not supposed to be able to call class methods if the class isn't instantiated! My method isn't static! What is happening?
The source code
Obviously the initialize is called from the main plugin file:
add_action('init', array('AffiliateMarketting', 'initialize'), 1);
My class looks like this:
class AffiliateMarketting
{
public function __construct()
{
// some initialization code
}
public function initialize()
{
add_action('woocommerce_before_single_product', array("AffiliateMarketting", "handleAffiliateReferral"));
}
public function handleAffiliateReferral($post)
{
$this->xxx(); // <---- offending function call
}
public function xxx()
{
}
}
The received error message is in fact Fatal error: Using $this when not in object context in <filename> on line <linenumber>.
You have to instantiate the class first. Something like this:
$affiliatemarketing = new AffiliateMarketing;
and then do the following:
add_action('init', array(&$affiliatemarketing, 'initialize'), 1);
Edit: forgot to add, your action in your method should be added like this:
add_action('woocommerce_before_single_product', array(&$this, "handleAffiliateReferral"));
You're not supposed to be. That's why you're getting an error.
I don't know exactly how you're registering the method (code would help), but probably, you're expecting Wordpress to take care of creating an instance, but that's not its role.
I found thought the Codex documented if the class name is specified using its string representation, then the add_action function will assume the call is to a static method.
On the other hand if and instance of the class is passed along then add_action will use that instance to make the method call.
Although Arman hasn't specified which php version he is using, I would assume it's probably 5.3.2 or 5.3.3. The error itself is rather similar to the one described in this question and the solution also would be to upgrade to the latest version of php 5.3.

Categories