'Call to undefined function' - Trying to call function from an included file - php

So I have two files, 'header.php' and 'pluginfile.php'
The function that I want to call resides in 'pluginfile.php' and is:
public function getNonSubscriptionAmount() {
$total = 0;
foreach($this->_items as $item) {
if(!$item->isSubscription()) {
$total += $item->getProductPrice() * $item->getQuantity();
}
else {
// item is subscription
$basePrice = $item->getBaseProductPrice();
Cart66Common::log('[' . basename(__FILE__) . ' - line ' . __LINE__ . "] Item is a subscription with base price $basePrice");
$total += $basePrice;
}
}
return $total;
}
So in 'header.php' I have:
<?php
include_once($_SERVER['DOCUMENT_ROOT']."/wp-content/plugins/plugin-name/folder/PluginFile.php");
print getNonSubscriptionAmount();
?>
This gives the following error when any page is loaded:
Fatal error: Call to undefined function getnonsubscriptionamount() in
/home/username/domain.com/wp-content/themes/theme/header.php on
line 72
I've spent a couple of hours now trying to figure this out alone and am getting nowhere! Any help much appreciated!

#Wiseguy looks like he had the right idea put in the comments.
You are declaring a method and not a function. Is the function the entirety of your plugin.php file or is there more? If it is everything, remove the public modifier and just declare
function getNonSubscriptionAmount() {
// code here
}
But from the looks of the code it is part of a larger class. If thats the case then #Wiseguy comment is right on, you need to instantiate a new object of the class in plugin.php and then the desired method.
$obj = new PluginClass();
$obj->getNonSubscriptionAmount();

You said:
The function that I want to call resides in 'plugin.php' and is:
And in your file you are including:
So in 'header.php' I have:
include_once($_SERVER['DOCUMENT_ROOT']."/wp-content/plugins/plugin-name/folder/PluginFile.php");
print getNonSubscriptionAmount();
You are not including 'plugin.php' which is were the function lives.
Header.php should include 'plugin.php', not 'PluginFile.php'.

Related

Creating custom function in separate php file which is accessible from controller

I want to write a function for catalog->controller->checkout->cart.php in Opencart 2.3.0.2
I have already written a logic to check priduct_id and action to be taken if particular product id is found.
Now I want to take this logic in separate function in separate php file so that it will become more manageable.
I created function in php file under system->helper and loaded it from startup.php.
Then I can call this function from cart.php but reference to variable $this is lost even if I am passing $this to this function.
My stripped down code looks like this
cart.php
//some code before this
if (!$json) {
// Check if Product is Addon
test($this);
//more code after this
customfunction.php
function test($this) {
// print_r("Test Called");
$temp = $this->request->post['product_id'];
if ($this->request->post['product_id'] == 142) {
$json['success'] = sprintf($this->language->get('text_success'), $this->url->link('product/product', 'product_id=' . $this->request->post['product_id']), $product_info['name'], $this->url->link('checkout/cart'));
$product_options = $this->model_catalog_product->getProductOptions($this->request->post['product_id']);
$product_option_id = $product_option['product_option_id'];
//more code
I am getting error for
$this->request->post['product_id'];
Can someone tell me how to call custom function from separate php file preserving reference to $this variable.
$this is reserved word in php:
The pseudo-variable $this is available when a method is called from
within an object context.
Try that instead:
function test($ctrl) {
$temp = $ctrl->request->post['product_id'];
if ($ctrl->request->post['product_id'] == 142) {
...

Function defined in included file breaking wordpress

Here is my code:
single-location.php
<?php
// include start_dates.php
include('start_dates.php'); // contians the start dates and a helper function contains()
$crazy = crazyness_rad(); // breaks the page for some reason
start_dates.php
<?php
// simple test function that returns a string...
function crazyness_rad() {
return 'WLHLHDFLDHFLDHF KJDHF KJDHF KLJDHF K';
}
And when I call this function from single-location.php it breaks the page...this works outside of wordpress just fine.
Why if I call a function defined in an include does it break? Thanks for the help with my noob question.
The error I get is:
Fatal error: Call to undefined function crazyness_rad() in C:\inetpub\larockwww\wp-content\themes\larock-academy\single-location.php on line 51
I just moved the function from the start_dates.php into the single-location.php and it works fine:
single-location.php
<?php
// include start_dates.php
include('start_dates.php'); // contains the start dates and a
// Moved into this file
function crazyness_rad() {
return 'WLHLHDFLDHFLDHF KJDHF KJDHF KLJDHF K';
}
$crazy = crazyness_rad(); // works fine IT seems the include isn't working..
seems that file start_dates.php is not in the correct path. Please include with the absolute path of the file . You can also try get_template_part function to include the file.
https://developer.wordpress.org/reference/functions/get_template_part/

declaring object in variable variable fatal error accessing empty property

Trying to crate objects dynamically for a plug in system (work in progress)
heres my code using $this->module->load_module('test'); to use the method that creates the dynamic objects. Following code is the function that loads the class's and makes use of an auto loader, i have checked that its getting the correct file etc.
<?php
class BaseModule {
function __construct() {
}
function load_module($module){
echo 'Module = '.$module.'<br />';
$object_name = $module . "Controller";
$this->$$module = new $object_name();
}
}
Here is a test module that it would load when invoking $this->module->load_module('test'); and it creates the object outputting the test strings via echo statements. Heres the code for the test module that was constructed. Which should cause no problems as there is not really a solution but just an output string, but posted any way.
<?php
class testController {
function __construct() {
echo 'test controller from modules <br />';
}
}
However when running the page i am getting some errors can any one help out?
Notice: Undefined variable: test in
/Applications/MAMP/htdocs/tealtique/application/modules/BaseModule.php on line 11
Fatal error: Cannot access empty property in
/Applications/MAMP/htdocs/tealtique/application/modules/BaseModule.php on line 11

Accessing object properties within a callback execution

Let's say I have the following code:
class RandomNumber{
public $number;
function __construct($range,$callback){
$this->number = rand(0,$range);
$callback();
}
}
$rnd = new RandomNumber(9,function(){
echo "Line 11: ".$rnd->number."\n"; // Not working: empty variable
echo "Line 12: ".$number."\n"; // Not working: empty variable
echo "Line 13: ".$this->number."\n"; // Not working: Fatal error: Using $this when not in object context on line 13
});
echo "Line 15: ".$rnd->number."\n"; // Working: echoed random number
So I'm trying to access the property (number) of the newly created object. And I can not guess how to do it properly. I have read some PHP documentation and tried to search Google for the solution but I missed the thing or I used wrong keywords for searching. I'd be happy if you will point me into the right direction.
It's barely possible, because the things are happening one after the another, as well as the function is not aware of the outside world. In your case $rnd is declared outside the function as well as it's not already initialized (it will be after the whole line is executed)
And yes, you are not able to use $this, but you can pass $this in order to inject the newly created object.
class RandomNumber{
public $number;
function __construct($range,$callback){
$this->number = rand(0,$range);
$callback($this);
}
}
$rnd = new RandomNumber(9,function($obj){
echo "Line 11: ".$obj->number."\n";
});
You define the function outside of the scope of the class, inside of it it works just fine.
And $rnd cant work inside of it, as it is not yet filled, this will happen after the constructor did its work.
This works:
class RandomNumber{
public $number;
function __construct($range,$callback){
$this->number = rand(0,$range);
$callback($this);
$call2 = function(){
echo "Line 7 : " .$this->number."\n"; // Works
};
$call2();
}
public function callback($callback){
$callback();
}
}
$rnd = new RandomNumber(9,function($rnd){
echo "Line 15: ".$rnd->number."\n"; // Works
});
$rnd->callback(function() use ($rnd) {
echo "Line 19: ".$rnd->number."\n"; // Works
});

php undefined variable error when calling class method

I have been writing procedural php for years and am very comfortable with it. Recently I decided to rework an existing site and switch to PDO and OOP. Everyone is telling me that this is a better way to go but the learning curve is killing me. When trying to call a class, I get the following.
Menu Builder
vbls: 5 1
Notice: Undefined variable: Menu in /home/lance/DallyPost/projectWebSite/trunk/1/core/modules/menuBuilder.php on line 9
Fatal error: Call to a member function menuFramework() on a non-object in /home/lance/DallyPost/projectWebSite/trunk/1/core/modules/menuBuilder.php on line 9
The procedure is that I have included menu.php at the top of index.php, prior to including the following script:
<?php
//menuBuilder.php
echo"<h2>$pageTitle</h2>";
$pub = $_URI_KEY['PUB'];
$dir = $_URI_KEY['DIRECTORY'];
echo"vbls: $pub $dir";
if($Menu->menuFramework("$pub", "$dir") === false) {
echo"The base menu framework failed to build correctly.";
}
else{
echo"<p>The base menu framework has been successfully constructed.</p>";
}
?>
As you can see, the above script calls a method in the Menu class:
<?php
//menu.php
class Menu{
private $db;
public function __construct($database) {
$this->db = $database;
}
public function menuFramework($pub, $directory){
$link = "/" . $directory . "/index.php/" . $pub . "/home/0/Home-Page/";
$inc = "core/menus/" . $pub . "category.php";
$file = "core/menus/" . $pub . "menuFramework.php";
$text = "<nav class=\"top-bar\" data-topbar>";
$text .= "<ul class=\"title-area\">";
$text .= "<li class=\"name\">";
$text .= "<h1>Home Page</h1>";
$text .= "</li>";
$text .= "</ul>";
$text .= "include($inc)";
$text .= "</nav>";
//write text to a file
if(file_put_contents($file, $text)){
return true;
}
else{
return false;
}
}
... rest of file not shown
Can you help me understand why I am getting this error. My understanding is that the variable was or should have been defined when I included menu.php, which was done before which was called a the top if index.php
Thanks
add this at the top of the script
$menu = new Menu($dbHandle);
That's not how classes work. You can't reference an entire class, Menu, with a variable, $Menu, to invoke instance methods.
You need to create an instance of your class on which to invoke methods:
$menu = new Menu(...);
You can create class-level "static" methods which are invoked on the class itself, but that syntax doesn't involve $Menu. You would use Menu::method_name() for that.
You are calling $Menu->
so your are a calling a variable called Menu, instead of the class Menu.
anyways, that function is not static, so you need to instantiate an object.
For that, add a this line:
$menu = new Menu($db);
where $db is your database object, if you really need it, or null if you dont (i cannot say with that code fragment)
and then call
$menu->menuFramework(...)

Categories