Call to a member function publish() - php

i have created a joomla component and when i click on publish and unpublish button in admin then i am getting such error.
Fatal error: Call to a member function publish() on boolean in ...\libraries\legacy\controller\admin.php on line 209
Please help
UPDATE
my View.html.php
require_once JPATH_COMPONENT . '/helpers/lab.php';
class labViewStructurelist extends JViewLegacy
{
protected $structurelist;
protected $pagination;
public $filterForm;
public $activeFilters;public $state;
public function display($tpl = null)
{
$this->structurelist = $this->get('Items');
$this->pagination = $this->get('Pagination');
$this->state = $this->get('State');
//print_r($this->pagination->pagesTotal);die();
$this->filterForm = $this->get('FilterForm');
$this->activeFilters = $this->get('ActiveFilters');
$this->addToolBar();
$this->sidebar = JHtmlSidebar::render();
if (count($errors = $this->get('Errors')))
{
JError::raiseError(500, implode('<br />', $errors));
return false;
}
return parent::display($tpl);
}
protected function addToolBar() {
JToolBarHelper::title( JText::_('COM_LAB_LAB_DDDD'), 'generic.png' );
JToolBarHelper::publish('Structurelist.publish');
JToolBarHelper::unpublish('Structurelist.unpublish');
JToolBarHelper::deleteList('', 'patients.delete', 'JTOOLBAR_DELETE');
JToolBarHelper::preferences('com_lab');
}
}
Controller/stricturelist.php
// No direct access to this file
defined('_JEXEC') or die('Restricted access');
// import Joomla controller library
jimport('joomla.application.component.controlleradmin');
class LabControllerStructurelist extends JControllerAdmin
{
public function getModel($name='Structurelist',$prefix='ssModel',$config=array('ignore_request'=>true))
{
$model=parent::getModel($name,$prefix,$config);
return $model;
}
}
models\structurelist.php
defined('_JEXEC') or die;
jimport('joomla.application.component.modellist');
JFormHelper::loadFieldClass('list');
class LabModelStructurelist extends JModelList{
public function __construct($config = array())
{
if (empty($config['filter_fields']))
{
$config['filter_fields'] = array(
'id', 'a.id',
'fullname', 'a.fullname',
);
$assoc = JLanguageAssociations::isEnabled();
if ($assoc)
{
$config['filter_fields'][] = 'association';
}
}
parent::__construct($config);
}
public function getListQuery()
{
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->select('*');
$query->from('#__ss_structure_tmp');
$search = $this->getState('filter.search');
$limit = $this->getState('filter.limit');
if (!empty($search)) {
$query->where('fullname LIKE "%' . $search .'%" ' );
}
if (!empty($limit)) {
$query->setLimit($limit);
}
return $query;
}
protected function populateState($ordering = 'a.fullname', $direction = 'asc')
{
$app = JFactory::getApplication();
if ($layout = $app->input->get('layout'))
{
$this->context .= '.' . $layout;
}
$search = $this->getUserStateFromRequest($this->context . '.filter.search', 'filter_search');
$this->setState('filter.search', $search);
parent::populateState();
}
}

You need to provide the model to your controller using the getModel() method. Look in the articles controller of the com_content for example.

You need to add a table file with the publish function within:
defined('_JEXEC') or die;
use Joomla\Utilities\ArrayHelper;
class labTableStructurelist extends JTable
{
/**
* Constructor
*
* #param JDatabase &$db A database connector object
*/
public function __construct(&$db)
{
parent::__construct('#__ss_structure_tmp', 'id', $db);
}
/**
* Overloaded bind function to pre-process the params.
*
* #param array $array Named array
* #param mixed $ignore Optional array or list of parameters to ignore
*
* #return null|string null is operation was satisfactory, otherwise returns an error
*
* #see JTable:bind
* #since 1.5
*/
public function bind($array, $ignore = '')
{
$input = JFactory::getApplication()->input;
$task = $input->getString('task', '');
if (($task == 'save' || $task == 'apply') && (!JFactory::getUser()->authorise('core.edit.state', 'com_lab.structurelist.'.$array['id']) && $array['state'] == 1))
{
$array['state'] = 0;
}
if ($array['id'] == 0)
{
$array['created_by'] = JFactory::getUser()->id;
}
if (isset($array['params']) && is_array($array['params']))
{
$registry = new JRegistry;
$registry->loadArray($array['params']);
$array['params'] = (string) $registry;
}
if (isset($array['metadata']) && is_array($array['metadata']))
{
$registry = new JRegistry;
$registry->loadArray($array['metadata']);
$array['metadata'] = (string) $registry;
}
if (!JFactory::getUser()->authorise('core.admin', 'com_lab.structurelist.' . $array['id']))
{
$actions = JAccess::getActionsFromFile(
JPATH_ADMINISTRATOR . '/components/com_lab/access.xml',
"/access/section[#name='user']/"
);
$default_actions = JAccess::getAssetRules('com_lab.structurelist.' . $array['id'])->getData();
$array_jaccess = array();
foreach ($actions as $action)
{
$array_jaccess[$action->name] = $default_actions[$action->name];
}
$array['rules'] = $this->JAccessRulestoArray($array_jaccess);
}
// Bind the rules for ACL where supported.
if (isset($array['rules']) && is_array($array['rules']))
{
$this->setRules($array['rules']);
}
return parent::bind($array, $ignore);
}
/**
* This function convert an array of JAccessRule objects into an rules array.
*
* #param array $jaccessrules An array of JAccessRule objects.
*
* #return array
*/
private function JAccessRulestoArray($jaccessrules)
{
$rules = array();
foreach ($jaccessrules as $action => $jaccess)
{
$actions = array();
foreach ($jaccess->getData() as $group => $allow)
{
$actions[$group] = ((bool) $allow);
}
$rules[$action] = $actions;
}
return $rules;
}
/**
* Overloaded check function
*
* #return bool
*/
public function check()
{
// If there is an ordering column and this is a new row then get the next ordering value
if (property_exists($this, 'ordering') && $this->id == 0)
{
$this->ordering = self::getNextOrder();
}
return parent::check();
}
/**
* Method to set the publishing state for a row or list of rows in the database
* table. The method respects checked out rows by other users and will attempt
* to checkin rows that it can after adjustments are made.
*
* #param mixed $pks An optional array of primary key values to update. If not
* set the instance property value is used.
* #param integer $state The publishing state. eg. [0 = unpublished, 1 = published]
* #param integer $userId The user id of the user performing the operation.
*
* #return boolean True on success.
*
* #since 1.0.4
*
* #throws Exception
*/
public function publish($pks = null, $state = 1, $userId = 0)
{
// Initialise variables.
$k = $this->_tbl_key;
// Sanitize input.
ArrayHelper::toInteger($pks);
$userId = (int) $userId;
$state = (int) $state;
// If there are no primary keys set check to see if the instance key is set.
if (empty($pks))
{
if ($this->$k)
{
$pks = array($this->$k);
}
// Nothing to set publishing state on, return false.
else
{
throw new Exception(500, JText::_('JLIB_DATABASE_ERROR_NO_ROWS_SELECTED'));
}
}
// Build the WHERE clause for the primary keys.
$where = $k . '=' . implode(' OR ' . $k . '=', $pks);
// Determine if there is checkin support for the table.
if (!property_exists($this, 'checked_out') || !property_exists($this, 'checked_out_time'))
{
$checkin = '';
}
else
{
$checkin = ' AND (checked_out = 0 OR checked_out = ' . (int) $userId . ')';
}
// Update the publishing state for rows with the given primary keys.
$this->_db->setQuery(
'UPDATE `' . $this->_tbl . '`' .
' SET `state` = ' . (int) $state .
' WHERE (' . $where . ')' .
$checkin
);
$this->_db->execute();
// If checkin is supported and all rows were adjusted, check them in.
if ($checkin && (count($pks) == $this->_db->getAffectedRows()))
{
// Checkin each row.
foreach ($pks as $pk)
{
$this->checkin($pk);
}
}
// If the JTable instance value is in the list of primary keys that were set, set the instance.
if (in_array($this->$k, $pks))
{
$this->state = $state;
}
return true;
}
/**
* Define a namespaced asset name for inclusion in the #__assets table
*
* #return string The asset name
*
* #see JTable::_getAssetName
*/
protected function _getAssetName()
{
$k = $this->_tbl_key;
return 'com_lab.structurelist.' . (int) $this->$k;
}
/**
* Returns the parent asset's id. If you have a tree structure, retrieve the parent's id using the external key field
*
* #param JTable $table Table name
* #param integer $id Id
*
* #see JTable::_getAssetParentId
*
* #return mixed The id on success, false on failure.
*/
protected function _getAssetParentId(JTable $table = null, $id = null)
{
// We will retrieve the parent-asset from the Asset-table
$assetParent = JTable::getInstance('Asset');
// Default: if no asset-parent can be found we take the global asset
$assetParentId = $assetParent->getRootId();
// The item has the component as asset-parent
$assetParent->loadByName('com_lab');
// Return the found asset-parent-id
if ($assetParent->id)
{
$assetParentId = $assetParent->id;
}
return $assetParentId;
}
/**
* Delete a record by id
*
* #param mixed $pk Primary key value to delete. Optional
*
* #return bool
*/
public function delete($pk = null)
{
$this->load($pk);
$result = parent::delete($pk);
return $result;
}
}
Please note, that this is just an example of a table file, I can't guarantee that this would work just by copy&paste. Please check com_content/table for another example.
Also add a getTable() to your List single item model:
public function getTable($type = 'view_name', $prefix = 'labTable', $config = array())
{
return JTable::getInstance($type, $prefix, $config);
}
Please check if file structure is correct:
List View
structurelist**s** -> list view with multiple items
|-> controller/structurelists.php
|-> models/structurelists.php
|-> view/structurelists/
Single View / List View (publish() for example)
structurelist -> single item view (edit view)
|-> models/structurelist.php (this is important for the publish() in the list view)
|-> models/forms/structurelist.xml
|-> tables/structurelist.php (this is important for the publish() in the list view)
|-> view/structurelist/
Feel free to comment if you need more help.

Related

I am having an issue with the twig template system

I have opencart 3 installed on my dev box and have suddenly started getting the following error:
Fatal error: Class Twig_Loader_Filesystem contains 2 abstract methods
and must therefore be declared abstract or implement the remaining
methods (Twig_LoaderInterface::isFresh,
Twig_ExistsLoaderInterface::exists) in
/mnt/c/wsl/server/opencart/system/library/template/Twig/Loader/Filesystem.php
on line 17
I have been working on a custom template and all was going fine until I changed something in the controller of the footer. Changing it back did not resolve the issue. I have also manually cleared the cache in the OC folder and the twig folder. I also did not have the cache setting set to off so I manually made this change in the db as I get the same error trying to get into the admin.
I am at a loss. I would love any help I could get.
Call Stack
{main}( )
start( )
require_once( '/mnt/c/wsl/server/opencart/system/framework.php' )
Router->dispatch( )
Router->execute( )
Action->execute( )
ControllerStartupRouter->index( )
Action->execute( )
ControllerCommonHome->index( )
Loader->controller( )
Action->execute( )
ControllerCommonColumnLeft->index( )
Loader->view( )
Template->render( )
Template\Twig->render( )
spl_autoload_call ( )
Twig_Autoloader::autoload( )
require( '/mnt/c/wsl/server/opencart/system/library/template/Twig/Loader/Filesystem.php'
)
Location
.../index.php:0
.../index.php:19
.../startup.php:104
.../framework.php:165
.../router.php:56
.../router.php:67
.../action.php:79
.../router.php:25
.../action.php:79
.../home.php:12
.../loader.php:48
.../action.php:79
.../column_left.php:72
.../loader.php:125
.../template.php:51
.../twig.php:20
.../twig.php:20
.../Autoloader.php:51
class Twig_Loader_Filesystem implements Twig_LoaderInterface, Twig_ExistsLoaderInterface
{
/** Identifier of the main namespace. */
const MAIN_NAMESPACE = '__main__';
protected $paths = array();
protected $cache = array();
protected $errorCache = array();
/**
* Constructor.
*
* #param string|array $paths A path or an array of paths where to look for templates
*/
public function __construct($paths = array())
{
if ($paths) {
$this->setPaths($paths);
}
}
/**
* Returns the paths to the templates.
*
* #param string $namespace A path namespace
*
* #return array The array of paths where to look for templates
*/
public function getPaths($namespace = self::MAIN_NAMESPACE)
{
return isset($this->paths[$namespace]) ? $this->paths[$namespace] : array();
}
/**
* Returns the path namespaces.
*
* The main namespace is always defined.
*
* #return array The array of defined namespaces
*/
public function getNamespaces()
{
return array_keys($this->paths);
}
/**
* Sets the paths where templates are stored.
*
* #param string|array $paths A path or an array of paths where to look for templates
* #param string $namespace A path namespace
*/
public function setPaths($paths, $namespace = self::MAIN_NAMESPACE)
{
if (!is_array($paths)) {
$paths = array($paths);
}
$this->paths[$namespace] = array();
foreach ($paths as $path) {
$this->addPath($path, $namespace);
}
}
/**
* Adds a path where templates are stored.
*
* #param string $path A path where to look for templates
* #param string $namespace A path name
*
* #throws Twig_Error_Loader
*/
public function addPath($path, $namespace = self::MAIN_NAMESPACE)
{
// invalidate the cache
$this->cache = $this->errorCache = array();
if (!is_dir($path)) {
throw new Twig_Error_Loader(sprintf('The "%s" directory does not exist.', $path));
}
$this->paths[$namespace][] = rtrim($path, '/\\');
}
/**
* Prepends a path where templates are stored.
*
* #param string $path A path where to look for templates
* #param string $namespace A path name
*
* #throws Twig_Error_Loader
*/
public function prependPath($path, $namespace = self::MAIN_NAMESPACE)
{
// invalidate the cache
$this->cache = $this->errorCache = array();
if (!is_dir($path)) {
throw new Twig_Error_Loader(sprintf('The "%s" directory does not exist.', $path));
}
$path = rtrim($path, '/\\');
if (!isset($this->paths[$namespace])) {
$this->paths[$namespace][] = $path;
} else {
array_unshift($this->paths[$namespace], $path);
}
}
/**
* {#inheritdoc}
*/
public function getSource($name)
{
return file_get_contents($this->findTemplate($name));
}
/**
* {#inheritdoc}
*/
public function getCacheKey($name)
{
return $this->findTemplate($name);
}
/**
* {#inheritdoc}
*/
public function exists($name)
{
$name = $this->normalizeName($name);
if (isset($this->cache[$name])) {
return true;
}
try {
return false !== $this->findTemplate($name, false);
} catch (Twig_Error_Loader $exception) {
return false;
}
}
/**
* {#inheritdoc}
*/
public function isFresh($name, $time)
{
return filemtime($this->findTemplate($name)) <= $time;
}
protected function findTemplate($name)
{
$throw = func_num_args() > 1 ? func_get_arg(1) : true;
$name = $this->normalizeName($name);
if (isset($this->cache[$name])) {
return $this->cache[$name];
}
if (isset($this->errorCache[$name])) {
if (!$throw) {
return false;
}
throw new Twig_Error_Loader($this->errorCache[$name]);
}
$this->validateName($name);
list($namespace, $shortname) = $this->parseName($name);
if (!isset($this->paths[$namespace])) {
$this->errorCache[$name] = sprintf('There are no registered paths for namespace "%s".', $namespace);
if (!$throw) {
return false;
}
throw new Twig_Error_Loader($this->errorCache[$name]);
}
foreach ($this->paths[$namespace] as $path) {
if (is_file($path.'/'.$shortname)) {
if (false !== $realpath = realpath($path.'/'.$shortname)) {
return $this->cache[$name] = $realpath;
}
return $this->cache[$name] = $path.'/'.$shortname;
}
}
$this->errorCache[$name] = sprintf('Unable to find template "%s" (looked into: %s).', $name, implode(', ', $this->paths[$namespace]));
if (!$throw) {
return false;
}
throw new Twig_Error_Loader($this->errorCache[$name]);
}
protected function parseName($name, $default = self::MAIN_NAMESPACE)
{
if (isset($name[0]) && '#' == $name[0]) {
if (false === $pos = strpos($name, '/')) {
throw new Twig_Error_Loader(sprintf('Malformed namespaced template name "%s" (expecting "#namespace/template_name").', $name));
}
$namespace = substr($name, 1, $pos - 1);
$shortname = substr($name, $pos + 1);
return array($namespace, $shortname);
}
return array($default, $name);
}
protected function normalizeName($name)
{
return preg_replace('#/{2,}#', '/', str_replace('\\', '/', (string) $name));
}
protected function validateName($name)
{
if (false !== strpos($name, "\0")) {
throw new Twig_Error_Loader('A template name cannot contain NUL bytes.');
}
$name = ltrim($name, '/');
$parts = explode('/', $name);
$level = 0;
foreach ($parts as $part) {
if ('..' === $part) {
--$level;
} elseif ('.' !== $part) {
++$level;
}
if ($level < 0) {
throw new Twig_Error_Loader(sprintf('Looks like you try to load a template outside configured directories (%s).', $name));
}
}
}
}

Woocommerce error ET_WC_Order::get_total()

I'm using Woocommerce with my Wordpress theme. The website is selling services. The template developer support is dead, they say woocommerce compatibility but there is small bug I need to find the fix myself but I don't know what to do.
When the client tries to add credit to his account he selects the value and goes to next screen where woocommerce payment gateways are shown, they are listed but 'Pay' button its not there. When I look into Wordpress wp-content debug log I got this errors:
[23-Jul-2018 10:15:58 UTC] PHP Strict Standards: Declaration of ET_WC_Order::get_total() should be compatible with WC_Abstract_Order::get_total($context = 'view') in /home/admin/public_html/mysite.com/wp-content/themes/mysite.com/includes/aecore/wc_integration/payment/ET_WC_Order.php on line 3
[23-Jul-2018 10:15:58 UTC] PHP Strict Standards: Declaration of ET_WC_Package::get_sku() should be compatible with WC_Product::get_sku($context = 'view') in /home/admin/public_html/mysite.com/wp-content/themes/mysite.com/includes/aecore/wc_integration/payment/ET_WC_Package.php on line 4
ET_WC_Order.php content:
<?php if(class_exists("WC_Abstract_Order")) {
class ET_WC_Order extends WC_Abstract_Order
{
protected $etOrder;
protected $cancel_url = "";
protected $received_url = "";
public function __construct($order = '')
{
$this->post_type = 'order';
$this->prices_include_tax = get_option('woocommerce_prices_include_tax') == 'yes' ? true : false;
$this->tax_display_cart = get_option('woocommerce_tax_display_cart');
$this->display_totals_ex_tax = $this->tax_display_cart == 'excl' ? true : false;
$this->display_cart_ex_tax = $this->tax_display_cart == 'excl' ? true : false;
$this->init($order);
}
public function get_refunds()
{
return array();
}
public function get_total_refunded()
{
return 0;
}
/**
* Init
*
* #param int|object|WC_Order $order
*/
protected function init($order)
{
if (is_numeric($order)) {
$this->id = absint($order);
$this->post = get_post($order);
$this->get_order($this->id);
} elseif ($order instanceof ET_WC_Order) {
$this->id = absint($order->id);
$this->ID = absint($order->id);
$this->post = $order->post;
$this->etOrder = $order->etOrder;
$this->populate($order->etOrder);
} elseif ($order instanceof AE_Order) {
$payData = $order->generate_data_to_pay();
$order->ID = $payData["ID"];
$this->etOrder = $order;
$this->populate($order);
// Billing email cam default to user if set
if (empty($this->billing_email) && !empty($this->customer_user)) {
$user = get_user_by('id', $this->customer_user);
$this->billing_email = $user->user_email;
}
} elseif ($order instanceof WP_Post || isset($order->ID)) {
$this->id = absint($order->ID);
$this->post = $order;
$this->get_order($this->id);
}
}
public function get_order($id = 0)
{
if (!$id) {
return false;
}
$this->etOrder = new AE_Order($id);
if ($this->etOrder) {
$payData = $this->etOrder->generate_data_to_pay();
$this->etOrder->ID = $payData["ID"];
$this->populate($this->etOrder);
return true;
}
return false;
}
/**
* Populate the order, like convert method
*
* #param mixed $result
*/
public function populate($result)
{
$orderData = $result->get_order_data();
// Standard post data
$this->id = $result->ID;
$this->order_date = $orderData['created_date'];
$this->modified_date = $orderData['created_date'];
$this->customer_message = '';
$this->customer_note = '';
$this->post_status = $orderData['status'];
// Billing email cam default to user if set
if (empty($this->billing_email) && !empty($this->customer_user)) {
$user = get_user_by('id', $this->customer_user);
$this->billing_email = $user->user_email;
}
$this->cancel_url = et_get_page_link('process-payment', array('paymentType' => $orderData['payment']));
$this->received_url = et_get_page_link('process-payment', array('paymentType' => $orderData['payment']));
}
public function get_shipping_address()
{
return "";
}
/**
* Get item of order
*
* #param string $type
* #return array
*/
public function get_items($type = '')
{
if (empty($type)) {
$type = array('line_item');
}
if (!is_array($type)) {
$type = array($type);
}
$type = array_map('esc_attr', $type);
$items = array();
if (in_array('line_item', $type)) {
$orderData = $this->etOrder->get_order_data();
if (isset($orderData["products"])) {
$index = 0;
foreach ($orderData["products"] as $id => $product) {
$items[$index]['name'] = $product['NAME'];
$items[$index]['product_id'] = $product['ID'];
$items[$index]['type'] = "line_item";
$items[$index]['qty'] = $product['QTY'];
$items[$index]['tax_class'] = '';
$items[$index]['line_subtotal'] = $product['AMT'];
$items[$index]['line_subtotal_tax'] = '0';
$items[$index]['item_meta'] = array();
$index++;
}
}
}
return $items;
}
/**
* Get total of order
* #author : Nguyễn Văn Được
* #return mixed
*/
public function get_total()
{
$orderData = $this->etOrder->get_order_data();
$total = $orderData["total"];
return $total;
}
/**
* Get order currency
* #author : Nguyễn Văn Được
* #return mixed
*/
public function get_order_currency()
{
$orderData = $this->etOrder->get_order_data();
return $orderData["currency"];
}
/**
* Get products from product item
* #author : Nguyễn Văn Được
*
* #param mixed $item
*
* #return bool|\ET_WC_Package
*/
public function get_product_from_item($item)
{
if (!empty($item['product_id'])) {
$_product = new ET_WC_Package($item['product_id']);
} else {
$_product = false;
}
return $_product;
}
public function get_checkout_order_received_url()
{
return $this->received_url;
}
public function set_checkout_order_received_url($received_url)
{
$this->received_url = $received_url;
}
public function get_cancel_order_url($redirect = '')
{
return $this->cancel_url;
}
public function set_cancel_order_url($cancel_url)
{
$this->cancel_url = $cancel_url;
}
/**
* Update order status
*
* #param string $new_status
* #param string $note
*/
public function update_status($new_status, $note = '', $manual = false)
{
if (!$this->id) {
return;
}
// Standardise status names.
$new_status = 'wc-' === substr($new_status, 0, 3) ? substr($new_status, 3) : $new_status;
$old_status = $this->get_status();
switch (strtoupper($new_status)) {
case 'COMPLETED':
case 'PUBLISH':
$this->post_status = 'publish';
break;
case 'PROCESSING' :
case 'ON-HOLD':
$this->post_status = 'pending';
break;
case 'CANCELLED' :
$this->post_status = 'draft';
break;
default:
$this->post_status = 'draft';
break;
}
$this->etOrder->post_status = $this->post_status;
$log = new WC_Logger();
$log->add('paypal', "Our Debug : " . $this->post_status);
wp_update_post(array('ID' => $this->etOrder->ID, 'post_status' => $this->post_status));
}
public function needs_shipping_address()
{
return false;
}
public function is_editable()
{
return parent::is_editable(); // TODO: Change the autogenerated stub
}
public function get_qty_refunded_for_item($item_id, $item_type = 'line_item')
{
$qty = 0;
return $qty;
}
public function get_total_refunded_for_item($item_id, $item_type = 'line_item')
{
$total = 0;
return $total * -1;
}
}
}
ET_WC_Package.php content:
<?php
if(class_exists("WooCommerce")) {
class ET_WC_Package extends WC_Product
{
protected $etPaynentPackage;
function __construct($product, $arg = array())
{
$this->product_type = 'pack';
parent::__construct($product);
}
public function get_sku()
{
return $this->post->ID;
}
public function is_virtual()
{
return true;
}
public function needs_shipping()
{
return false;
}
public function get_permalink() {
return get_permalink( $this->id );
}
}
}
PHP Strict Standards: Declaration of ET_WC_Order::get_total() should
be compatible with WC_Abstract_Order::get_total($context = 'view')
Change the get_total() function in ET_WC_Order.php to be
public function get_total($context = 'view')
{
$orderData = $this->etOrder->get_order_data();
$total = $orderData["total"];
return $total;
}
PHP Strict Standards: Declaration of ET_WC_Package::get_sku() should
be compatible with WC_Product::get_sku($context = 'view')
Change the get_sku() function in ET_WC_Package.php to be
public function get_sku($context = 'view')
{
return $this->post->ID;
}

PHP strict standards error text added to results on the page

This is the error message generated:
Strict Standards: call_user_func_array() expects parameter 1 to be a
valid callback, non-static method
ModCareercoachoccupationsHelper::getRelated() should not be called
statically in
/customers/f/0/0/studiomitchell.agency/httpd.www/libraries/joomla/cache/controller/callback.php
on line 152
<?php
/**
* #package Joomla.Platform
* #subpackage Cache
*
* #copyright Copyright (C) 2005 - 2016 Open Source Matters, Inc. All rights reserved.
* #license GNU General Public License version 2 or later; see LICENSE
*/
defined('JPATH_PLATFORM') or die;
/**
* Joomla! Cache callback type object
*
* #since 11.1
*/
class JCacheControllerCallback extends JCacheController
{
/**
* Executes a cacheable callback if not found in cache else returns cached output and result
*
* Since arguments to this function are read with func_get_args you can pass any number of arguments to this method
* as long as the first argument passed is the callback definition.
*
* The callback definition can be in several forms:
* - Standard PHP Callback array see <https://secure.php.net/callback> [recommended]
* - Function name as a string eg. 'foo' for function foo()
* - Static method name as a string eg. 'MyClass::myMethod' for method myMethod() of class MyClass
*
* #return mixed Result of the callback
*
* #since 11.1
*/
public function call()
{
// Get callback and arguments
$args = func_get_args();
$callback = array_shift($args);
return $this->get($callback, $args);
}
/**
* Executes a cacheable callback if not found in cache else returns cached output and result
*
* #param mixed $callback Callback or string shorthand for a callback
* #param array $args Callback arguments
* #param mixed $id Cache ID
* #param boolean $wrkarounds True to use wrkarounds
* #param array $woptions Workaround options
*
* #return mixed Result of the callback
*
* #since 11.1
*/
public function get($callback, $args = array(), $id = false, $wrkarounds = false, $woptions = array())
{
// Normalize callback
if (is_array($callback))
{
// We have a standard php callback array -- do nothing
}
elseif (strstr($callback, '::'))
{
// This is shorthand for a static method callback classname::methodname
list ($class, $method) = explode('::', $callback);
$callback = array(trim($class), trim($method));
}
elseif (strstr($callback, '->'))
{
/*
* This is a really not so smart way of doing this... we provide this for backward compatability but this
* WILL! disappear in a future version. If you are using this syntax change your code to use the standard
* PHP callback array syntax: <https://secure.php.net/callback>
*
* We have to use some silly global notation to pull it off and this is very unreliable
*/
list ($object_123456789, $method) = explode('->', $callback);
global $$object_123456789;
$callback = array($$object_123456789, $method);
}
if (!$id)
{
// Generate an ID
$id = $this->_makeId($callback, $args);
}
$data = $this->cache->get($id);
$locktest = new stdClass;
$locktest->locked = null;
$locktest->locklooped = null;
if ($data === false)
{
$locktest = $this->cache->lock($id);
if ($locktest->locked == true && $locktest->locklooped == true)
{
$data = $this->cache->get($id);
}
}
$coptions = array();
if ($data !== false)
{
$cached = unserialize(trim($data));
$coptions['mergehead'] = isset($woptions['mergehead']) ? $woptions['mergehead'] : 0;
$output = ($wrkarounds == false) ? $cached['output'] : JCache::getWorkarounds($cached['output'], $coptions);
$result = $cached['result'];
if ($locktest->locked == true)
{
$this->cache->unlock($id);
}
}
else
{
if (!is_array($args))
{
$referenceArgs = !empty($args) ? array(&$args) : array();
}
else
{
$referenceArgs = &$args;
}
if ($locktest->locked == false)
{
$locktest = $this->cache->lock($id);
}
if (isset($woptions['modulemode']) && $woptions['modulemode'] == 1)
{
$document = JFactory::getDocument();
$coptions['modulemode'] = 1;
if (method_exists($document, 'getHeadData'))
{
$coptions['headerbefore'] = $document->getHeadData();
}
}
else
{
$coptions['modulemode'] = 0;
}
ob_start();
ob_implicit_flush(false);
$result = call_user_func_array($callback, $referenceArgs);
$output = ob_get_clean();
$coptions['nopathway'] = isset($woptions['nopathway']) ? $woptions['nopathway'] : 1;
$coptions['nohead'] = isset($woptions['nohead']) ? $woptions['nohead'] : 1;
$coptions['nomodules'] = isset($woptions['nomodules']) ? $woptions['nomodules'] : 1;
$cached = array(
'output' => ($wrkarounds == false) ? $output : JCache::setWorkarounds($output, $coptions),
'result' => $result,
);
// Store the cache data
$this->cache->store(serialize($cached), $id);
if ($locktest->locked == true)
{
$this->cache->unlock($id);
}
}
echo $output;
return $result;
}
/**
* Generate a callback cache ID
*
* #param callback $callback Callback to cache
* #param array $args Arguments to the callback method to cache
*
* #return string MD5 Hash
*
* #since 11.1
*/
protected function _makeId($callback, $args)
{
if (is_array($callback) && is_object($callback[0]))
{
$vars = get_object_vars($callback[0]);
$vars[] = strtolower(get_class($callback[0]));
$callback[0] = $vars;
}
return md5(serialize(array($callback, $args)));
}
}
The site retrieves the data but with this text error also above
the listing.
The callback.php line 152 is as follows:
$result = call_user_func_array($callback, $referenceArgs);
Any help would be great. Thanks
You'll get this error if you define the method non-statically:
class Foo {
public function bar() {
}
}
And then define $callback as either a string:
$callback = 'Foo::bar';
Or an array of strings:
$callback = ['Foo', 'bar'];
And then use it as an argument to call_user_func_array():
call_user_func_array($callback, []);
To avoid this, you can either define the method statically:
public static function bar() { ... }
Or use an instantiated object in your callback:
$callback = [new Foo(), 'bar'];

PHP: Warning: array_map(): Argument #2 should be an array

I have a script that works perfect in ubuntu, recently I copied the exact same script to centos6 server
and I'm getting the following error:
PHP Warning: array_map(): Argument #2 should be an array in /copy_scripts/classes/Vserver.class.php on line 245
the code
/**
* Get an array of open files
* #param array $aExt
* #return array of arrays ['views','size','path']
*/
public function getOpenFiles($aExt=array()) {
$aOpenFiles = self::GetList(self::$sLogOpenFiles);
$aOpenFiles = array_map( create_function('$v', '
$v = trim($v);
$aFile = preg_split("#[\t\s]+#",$v);
$oFile = new VserverFile($aFile[2]);
$oFile->setViews($aFile[0]);
return $oFile;'),
$aOpenFiles
);
//echo "<pre>";
//print_r($aOpenFiles);
return $aOpenFiles;
}
Can it be the difference between php versions?
centos:
PHP 5.3.3 (cli) (built: Jul 3 2012 16:53:21)
ubuntu
PHP 5.3.10-2 (cli) (built: Feb 20 2012 19:39:00)
Copyright (c) 1997-2012 The PHP Group
Zend Engine v2.3.0, Copyright (c) 1998-2012 Zend Technologies
what I've tried so far:
changing setting in php.ini a restarting php.
the complete code:
<?php
/**
*
* Global Video Server class
* Singleton class
* Has methods to manipulate files
* #author kpoxas
*
*/
class Vserver {
static protected $oInstance=null;
static protected $iTimeStart, $iTimeEnd;
const FILE_NOEXIST = -2;
const FILE_ZEROSIZE = -4;
const FILE_DIFF = -8;
/*
* Path /var/www/HDD_PATH/
*/
static public $sHDDPath = null;
/*
* Path /var/www/SSD_PATH/
*/
static public $sSSDPath = null;
/*
* Folder same on every RAID.../FOLDER/...
*/
static public $sHTTPFolder = null;
/*
* Open Files Log
*/
static public $sLogOpenFiles = null;
/*
* Limit of Free space on SSD in percents
*/
static public $iSSDUsage = 90;
/*
* Limit of Free space on SSD in percents (not delete below)
*/
static public $iSSDDeleteUsage = 80;
/*
* Limit of Free space on SSD in bytes (not delete below)
*/
static public $iSSDDeleteUsageAbsolute = 5368709120;
/*
* Min views count of file to copy
*/
static public $iMinViews = 2;
/*
* Search within files older than $iDaysToDelete days
*/
static public $iDaysToDelete = 1;
/*
* Test Mode
* File manipulations aren't executed
* Only log mode
*/
static public $bTest = false;
/*
* Store openfiles.txt log
*/
static protected $sOpenFiles = null;
/**
* Äåñêðèïòîð áëîêèðóþùåãî ôàéëà
*
* #var string
*/
protected $oLockFile=null;
/**
* Singleton Object implementation
*
* #return VSERVER
*/
static public function getInstance() {
if (isset(self::$oInstance) and (self::$oInstance instanceof self)) {
return self::$oInstance;
} else {
self::$oInstance= new self();
return self::$oInstance;
}
}
/**
* Get Log content
* #param string $sLogPath
* #return string
*/
static public function GetLog($sLogPath) {
if ($s = #file_get_contents($sLogPath)) {
$s = trim($s);
if (!empty($s)) {
return $s;
}
}
return false;
}
/**
* Get Log content in list mode divided by EOL
* #param string $sLogPath
* #return array
*/
static public function GetList($sLogPath) {
if ($sList = self::GetLog($sLogPath)) {
return explode(PHP_EOL,trim($sList));
}
}
/**
* Check if directory exists and chmod 775
* #param $directory
*/
static public function CheckDirectory($directory) {
$directory = rtrim($directory, '/\\');
if (is_dir($directory)) #chmod($directory, 0775);
else {
if (!mkdir($directory, 0755, true)) {
//self::AddError ('Directory does not exist', $directory);
return false;
}
}
}
/**
* Check if file exist
* Check if file has zero size
* #param string $filename
*/
static public function CheckFile($filename) {
if (file_exists($filename) && !is_file($filename)) {
self::log("NO VALID FILEPATH: {$filename}");
return false;
} else if(!file_exists($filename)) {
self::log("FILE DOESN'T EXIST: {$filename}");
return self::FILE_NOEXIST;
} else if(!filesize($filename)) {
self::log("FILE ZEROSIZE: {$filename}");
return self::FILE_ZEROSIZE;
}
else return true;
}
/**
* Check if file1 is identical to file2
* #param string $filename1
* #param string $filename2
*/
static public function CheckIdentity($filename1, $filename2) {
if (self::CheckFile($filename1)>0 && self::CheckFile($filename2)>0) {
if (filesize($filename1)===filesize($filename2)) {
self::log("FILES: {$filename1} AND {$filename2} ARE IDENTICAL");
return true;
}
self::log("FILES: {$filename1} AND {$filename2} ARE DIFFERENT");
return false;
}
}
/**
* Copy file from $source to $dest
* Make www-data owner
* Make perms 755
*/
static public function Copy($source, $dest = null) {
self::log("COPY {$source} TO {$dest}");
if (self::$bTest) return true;
self::CheckDirectory(dirname($dest));
// copy
$sCmd = "cp -f '{$source}' '{$dest}'";
self::exec($sCmd);
// chown
$sCmdChown = "chown www-data:www-data '{$dest}'";
self::exec($sCmdChown);
// chmod
$sCmdChmod = "chmod 775 '{$dest}'";
self::exec($sCmdChmod);
return true;
}
/**
* Delete file
*/
static public function Delete($source) {
self::log("DELETE {$source}");
if (self::$bTest) return true;
// chmod
$sCmdChmod = "rm '{$source}'";
self::exec($sCmdChmod);
}
/**
* Get free space of catalog or storage in bytes
* #param string $sDir
*/
static public function GetFreeSpace($sDir = '') {
return disk_free_space($sDir);
}
/**
* Get total space of catalog or storage in bytes
* #param string $sDir
*/
static public function GetTotalSpace($sDir = '') {
return disk_total_space($sDir);
}
/**
* Get used space of catalog or storage in percents
* #param string $sDir
*/
static public function GetUsage($sDir = '') {
//$sCmd = "df -k {$sDir} | grep -Eo '[0-9]+%'";
//return intval(self::exec($sCmd));
return round(1-self::GetFreeSpace($sDir)/self::GetTotalSpace($sDir),4)*100;
}
/**
* Exec command wrapper
*/
static public function exec($sCmd = null, &$aVar=null) {
if (empty($sCmd)) {
return;
}
self::log($sCmd);
return exec($sCmd, $aVar);
}
static public function log($sStr) {
echo "{$sStr}<br>\n";
}
/**
* Get open files log
* #return string
*/
static public function getOpenFilesContent() {
if (self::$sOpenFiles === null) {
self::$sOpenFiles = self::GetLog(self::$sLogOpenFiles);
}
return self::$sOpenFiles;
}
/**
* Get an array of open files
* #param array $aExt
* #return array of arrays ['views','size','path']
*/
public function getOpenFiles($aExt=array()) {
$aOpenFiles = self::GetList(self::$sLogOpenFiles);
$aOpenFiles = array_map( create_function('$v', '
$v = trim($v);
$aFile = preg_split("#[\t\s]+#",$v);
$oFile = new VserverFile($aFile[2]);
$oFile->setViews($aFile[0]);
return $oFile;'),
$aOpenFiles
);
//echo "<pre>";
//print_r($aOpenFiles);
return $aOpenFiles;
}
public function getFileList($sDir=null, $aExt=array('flv','mp4'), $sGrep='') {
if (!$sDir || empty($aExt)) return;
$aCmdExt = "\( -name '*."
.implode("' -o -name '*.",$aExt)
."' \)";
$sCmd = "find {$sDir} {$aCmdExt} -mmin +".self::$iDaysToDelete."";
// sort by date
//$sCmd = "find {$sDir} {$aCmdExt} -printf '%T# %p\n'| sort -k 1n | cut -d' ' -f2-";
if (!empty($sGrep)) {
$sCmd.= " | {$sGrep}";
}
self::exec($sCmd,$aFiles);
return $aFiles;
}
/**
*
* Get list of storages
*/
public function getStorages() {
$sCmd = "df -k | grep -Eo 'storage[0-9]+$'";
self::exec($sCmd,$aStorages);
return $aStorages;
}
/**
*
* Get list of megastorages
*/
public function getMegaStorages() {
$sCmd = "df -k | sort -k5 -r | grep -Eo 'megastorage[0-9]+$'";
self::exec($sCmd,$aStorages);
return $aStorages;
}
/**
* Copy opened files to SSD
*/
public function copyToSSD() {
$this->setLock(__FUNCTION__.'.lock');
if($this->isLock()) {
self::log("Process has already started.");
return;
}
$iCopied = 0;
$iIgnored = 0;
$aOpenedFiles = $this->GetOpenFiles();
foreach ($aOpenedFiles as $oFile) {
if (self::GetUsage(self::$sSSDPath) < self::$iSSDUsage) {
if ($oFile->getViews() >=self::$iMinViews && $oFile->synchronize()) $iCopied++;
else $iIgnored++;
} else {
break;
}
}
self::log("COPIED: {$iCopied}");
self::log("IGNORED: {$iIgnored}");
self::log("SSD USAGE: ".self::GetUsage(self::$sSSDPath)."%");
}
/**
* DELETE FROM SSD
*/
public function deleteFromSSD() {
$this->setLock(__FUNCTION__.'.lock');
if($this->isLock()) {
self::log("Process has already started.");
return;
}
$iDeleted = 0;
$iIgnored = 0;
/*
* Get megastorages sorted by usage desc,
*/
$aMegaStorages = $this->getMegaStorages();
foreach ($aMegaStorages as &$sMegaStorage) {
/*
* Get files in current megastorage
*/
$aFileList = $this->getFileList('/'.$sMegaStorage);
if (empty($aFileList)) {
self::log("NO FILES FOUND in {$sMegaStorage}");
continue;
}
$aFileList = array_map(
create_function('$v', '
$oFile = new VserverFile(trim($v));
return $oFile;
'),
$aFileList
);
/*
* Delete files until appropriate usage
*/
$iFreeSpace = self::GetFreeSpace('/'.$sMegaStorage);
$iTotalSpace = self::GetTotalSpace('/'.$sMegaStorage);
foreach ($aFileList as &$oFile) {
$iUsageCurrent = round(1-$iFreeSpace/$iTotalSpace,4)*100;
self::Log($sMegaStorage." ".$iUsageCurrent."%");
if ($iUsageCurrent > self::$iSSDDeleteUsage) {
if (!$oFile->isOpened()) {
$iFreeSpace += $oFile->getSize();
$oFile->synchronize();
$oFile->deleteFromSSD();
$iDeleted++;
} else $iIgnored++;
} else {
break;
}
}
}
/*
$aFileList = $this->getFileList(self::$sSSDPath);
if (empty($aFileList)) {
self::log("NO FILES FOUND");
return;
}
$aFileList = array_map(
create_function('$v', '
$oFile = new VserverFile(trim($v));
return $oFile;
'),
$aFileList
);
foreach ($aFileList as $oFile) {
if (self::GetUsage(self::$sSSDPath) > self::$iSSDDeleteUsage) {
if (!$oFile->isOpened()) {
$oFile->synchronize();
$oFile->deleteFromSSD();
$iDeleted++;
} else $iIgnored++;
} else {
break;
}
}
*/
self::log("DELETED: {$iDeleted}");
self::log("IGNORED: {$iIgnored}");
self::log("SSD USAGE: ".self::GetUsage(self::$sSSDPath)."%");
}
/**
* DELETE FROM SSD
* USING ABSOLUTE VALUE of $iSSDDeleteUsageAbsolute
*/
public function deleteFromSSDAbsolute() {
$this->setLock(__FUNCTION__.'.lock');
if($this->isLock()) {
self::log("Process has already started.");
return;
}
$iDeleted = 0;
$iIgnored = 0;
/*
* Get megastorages sorted by usage desc,
*/
$aMegaStorages = $this->getMegaStorages();
foreach ($aMegaStorages as &$sMegaStorage) {
/*
* Get files in current megastorage
*/
$aFileList = $this->getFileList('/'.$sMegaStorage);
if (empty($aFileList)) {
self::log("NO FILES FOUND in {$sMegaStorage}");
continue;
}
$aFileList = array_map(
create_function('$v', '
$oFile = new VserverFile(trim($v));
return $oFile;
'),
$aFileList
);
/*
* Delete files until appropriate usage
*/
$iFreeSpace = self::GetFreeSpace('/'.$sMegaStorage);
foreach ($aFileList as &$oFile) {
self::Log($sMegaStorage." ".(round($iFreeSpace/1024/1024/1024,2))." G");
if ($iFreeSpace < self::$iSSDDeleteUsageAbsolute) {
if (!$oFile->isOpened()) {
$iFreeSpace += $oFile->getSize();
$oFile->synchronize();
$oFile->deleteFromSSD();
$iDeleted++;
} else $iIgnored++;
} else {
break;
}
}
}
self::log("DELETED: {$iDeleted}");
self::log("IGNORED: {$iIgnored}");
self::log("FREE SPACE: ".(round($iFreeSpace/1024/1024/1024,2))." G");
}
/**
*
* Get Identical files on storages
*/
public function getIdentical() {
$this->setLock(__FUNCTION__.'.lock');
if($this->isLock()) {
self::log("Process has already started.");
return;
}
$aStorages = $this->getStorages();
foreach ($aStorages as &$sStorage) {
$sDir = "/{$sStorage}/".self::$sHTTPFolder;
$aList[$sStorage] = $this->getFileList($sDir,array('flv'), "grep -Eo '".self::$sHTTPFolder.".*$'");
}
$iStorages = sizeof($aList);
for ($i=0; $i<$iStorages; $i++) {
reset($aList);
$sPrimaryStorage = key($aList);
$aPrimaryFiles = array_shift($aList);
foreach($aList as $sSecondaryStorage=>&$aSecondaryFiles) {
self::log("{$sPrimaryStorage} <-- {$sSecondaryStorage}");
//array of identical files
$aIdentical = array_intersect($aPrimaryFiles, $aSecondaryFiles);
if (!empty($aIdentical)) {
// get sizes
foreach ($aIdentical as $sFile) {
$iPrimaryPath = "/{$sPrimaryStorage}/".$sFile;
$iPrimarySize = filesize($iPrimaryPath);
$iSecondaryPath = "/{$sSecondaryStorage}/".$sFile;
$iSecondarySize = filesize($iSecondaryPath);
self::log("| {$iPrimaryPath} <-- {$iPrimarySize}");
self::log("| {$iSecondaryPath} <-- {$iSecondarySize}");
// delete if sizes are identical
if ($iPrimarySize == $iSecondarySize) self::Delete($iSecondaryPath);
// if any have null size
else if ($iPrimarySize * $iSecondarySize) continue;
else if (filectime($iPrimarySize)>filectime($iSecondaryPath)) self::Delete($iSecondaryPath);
else if (filectime($iSecondaryPath)>filectime($iPrimarySize)) self::Delete($iPrimarySize);
}
}
}
}
//echo "<pre>";
//print_r(array_intersect($aPrimaryFiles, $aSecondaryFiles));
//echo "</pre>";
}
/**
* Ñîçäàåò áëîêèðîâêó íà ïðîöåññ
*/
public function setLock($sLockFile=null) {
if(!empty($sLockFile)) {
$this->oLockFile=fopen($sLockFile,'a');
}
}
/**
* Ïðîâåðÿåò óíèêàëüíîñòü ñîçäàâàåìîãî ïðîöåññà
*/
public function isLock() {
return ($this->oLockFile && !flock($this->oLockFile, LOCK_EX|LOCK_NB));
}
/**
* Ñíèìàåò áëîêèðîâêó íà ïîâòîðíûé ïðîöåññ
*/
public function unsetLock() {
return ($this->oLockFile && #flock($this->oLockFile, LOCK_UN));
}
public function __construct() {
self::$iTimeStart = microtime(true);
}
public function __destruct() {
self::$iTimeEnd = microtime(true);
$iTimeExecution = round(self::$iTimeEnd - self::$iTimeStart,3);
$iUsageMem = memory_get_usage(true)/1024/1024; //Mb
$iUsageMemPeak = memory_get_peak_usage(true)/1024/1024; //Mb
self::log("Execution time: {$iTimeExecution} s");
self::log("Memory Usage: {$iUsageMem} Mb");
self::log("Memory Peak Usage: {$iUsageMemPeak} Mb");
$this->unsetLock();
}
/**
* Class autoloader
*
* #param unknown_type $sClassName
*/
public static function autoload($sClassName) {
require_once("{$sClassName}.class.php");
}
}
spl_autoload_register(array('Vserver','autoload'));
?>
Since array_map complains about $aOpenFiles not being an array you might want to take a look at that variable.
public function getOpenFiles($aExt=array()) {
$aOpenFiles = self::GetList(self::$sLogOpenFiles);
if ( !is_array($aOpenFiles) ) {
var_dump($aOpenFiles);
die('not an array');
}
$aOpenFiles = array_map( ...
quote:
static public function GetList($sLogPath) {
if ($sList = self::GetLog($sLogPath)) {
return explode(PHP_EOL,trim($sList));
}
}
... and if $sList evaluates to false (which may very well happen, since GetLog returns false on some conditions) this function returns nothing.
You have to check for that condition somewhere. Where depends on how you want the script to react on what condition. e.g.
static public function GetList($sLogPath) {
if ($sList = self::GetLog($sLogPath)) {
return explode(PHP_EOL,trim($sList));
}
return array();
}
would "fix" the error, but if that's feasible is another question; it may only "hide" a symptom - not the underlying problem. Must there be a log file? Must GetList(GetLog()) return a (non-empty) array? and so on and on....

PHP foreach over an array of objects

I'm trying to use a foreach loop for an array of objects. Inside of the BeginBattle() method I want to iterate through all of the objects and increment their played count automatically. Unfortunately, the web browser shows I have an error: Fatal error: Call to a member function BattleInitiated() on a non-object in /nfs/c05/h01/mnt/70299/domains/munchkinparty.neededspace.net/html/Battle.php on line 75
Any ideas?
<?php
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
* Description of Battle
*
* #author joshualowry
*/
class Battle {
/**
*
* #var <type>
*/
private $_players;
/**
*
* #var <type>
*/
private $_battleInProgress;
/**
*
*/
public function Battle(){
$this->_players = array();
$this->_battleInProgress = FALSE;
}
/**
*
* #param <type> $player
* #return <type>
*/
public function AddPlayer($player){
if(!$this->_battleInProgress)
$this->_players[] = $player;
else
return;
//Spit some error
}
/**
*
* #param <type> $player
* #return <type>
*/
public function BattleWon($player){
if($player != NULL)
$player->BattleWon();
else
return;
//Spit some error
}
/** GetPlayerByName Get the player's object by the player's name field.
*
* #param <type> $playerName
* #return <type>
*/
public function GetPlayerByName($playerName){
foreach($this->_players as &$player) {
if($player->GetName() == $playerName)
return $player;
}
return NULL;
}
/**
*
*/
public function BeginBattle(){
$this->_battleInProgress = TRUE;
foreach($this->_players as $player){
$player->BattleInitiated();
}
}
/**
*
*/
public function DisplayCurrentBoard() {
echo "Name Alias Wins Battles<br/>";
foreach($this->_players as &$player){
echo "$player->GetName() $player->GetAlias() $player->GetWins() $player->GetBattles()<br/>";
}
}
}
?>
This is where everything is declared and called:
<?php
include 'Battle.php';
include 'Person.php';
include 'Player.php';
$currentBattle = new Battle();
$playerA = new Player("JohnnyDanger","John",0,0);
$playerB = new Player("JoshTheJest","Josh",0,0);
$PlayerC = new Player("CarbQueen","Nicole",0,0);
$currentBattle->AddPlayer($playerA);
$currentBattle->AddPlayer($playerB);
$currentBattle->AddPlayer($playerC);
$currentBattle->BeginBattle();
$currentBattle->BattleWon($currentBattle->GetPlayerByName("Josh"));
$currentBattle->DisplayCurrentBoard();
?>
The Player Class
<?php
/**
* Description of Player
*
* #author joshualowry
*/
class Player extends Person {
private $_alias;
private $_wins;
private $_battles;
public function Player($name, $alias, $wins, $battles) {
parent::SetName($name);
$this->_alias = $alias;
$this->_battles = $battles;
if($battles == 0) {
$this->_wins = 0;
}
else {
$this->_wins = $wins;
}
}
protected function SetAlias($value){
$this->_alias = $value;
}
public function GetAlias(){
return $this->_alias;
}
protected function SetBattles($value) {
$this->_battles = $value;
}
public function GetBattles(){
return $this->_battles;
}
protected function SetWins($value) {
$this->_wins = $value;
}
public function GetWins() {
return $this->_wins;
}
public function BattleWon(){
$this->_wins += 1;
}
public function BattleInitiated(){
$this->_battles += 1;
}
}
?>
The error message indicates that you are trying to all the BattleInitiated() method on something that wasn't an object.
Judging from your code, the problem seems to be with this loop, in the BeginBattle() method :
foreach($this->_players as $player){
$player->BattleInitiated();
}
Which means $player, at least one in your array, is probably not an object ; maybe it's null, or an array ?
To know more, you should use var_dump to display the content of $this->_players before the loop, just to make sure it contains what you expect it to :
public function BeginBattle(){
var_dump($this->_players);
$this->_battleInProgress = TRUE;
foreach($this->_players as $player){
$player->BattleInitiated();
}
}
If $this->_players doesn't contain what you expect it to (and it probably doesn't !), you'll then have to find out why...
Considering $this->_players is modified by the AddPlayer() method, which adds what it receives to the end of the array, I would bet that AddPlayer() is called at least once without a correct $player as a parameter.
To help with that, you could use var_dump on the $player being added :
public function AddPlayer($player){
var_dump($player);
if(!$this->_battleInProgress)
$this->_players[] = $player;
else
return;
//Spit some error
}
If that var_dump indicates at least once that $player is not an object (for instance, it's null, or an array, or a string, ...), that's the cause of your Fatal Error.
don't you see it??
it's all because of a small typo:
$playerA = new Player("JohnnyDanger","John",0,0);
$playerB = new Player("JoshTheJest","Josh",0,0);
$PlayerC = new Player("CarbQueen","Nicole",0,0);
$currentBattle->AddPlayer($playerA);
$currentBattle->AddPlayer($playerB);
$currentBattle->AddPlayer($playerC);
declared: $_P_layerC
used: $_p_layerC
correct that and you're good to go
Your $player variable is either null or not an Object of the type you want it to be.
PlayerObject is what ever your class name for player is.
For example
$battle=new Battle();
$player1=new PlayerObject();
$player2="player";
$battle->AddPlayer($player1);
$battle->AddPlayer($player2);
$battle->BeginBattle();
when you call BeginBattle() the $player1->BattleInitiated(); will be successful but the $player2->BattleInitiated() will give you the fatal error and stop your code from running. same if $player2 was null, an integer or something that is not PlayerObject.

Categories