I'm trying to implement a DataTable class in php which will be basically a table to contain data just like an sql table and will be made of array()
The class is defined as followed:
class DataTable{
protected static $tabela; // table
//columns and strips, each column point to a strip
public function __construct($colunas, $faixas) {
$this->tabela = array();
$this->constroiDt($colunas, $faixas); //builds the table
}
public function getRows($where){
// todo
}
public static function getTabela(){
return $this->tabela;
}
private function constroiDt($colunas, $faixas){
if(count($colunas)!= count($faixas)){
$this->tabela = null;
return;
}
$i=0;
foreach($colunas as $cl){
$this->tabela = array_merge($this->tabela, array($cl => $faixas[$i]));
$i += $i + 1;
}
// the result will be an array like ('col1' => ('val1','val2'), 'col2' => ('val1','val2'))
// if I want to access a value, just type array['col1'][0] for example
}
}
Outside of the class function, when I create an example DT and try to access it, it seems that will work:
$columns = array("name", "age");
$strips = array(array("someone","another person"),array("20","30"));
$dt1 = new DataTable($columns, $strips);
var_dump($dt1); // will print:
// object(DataTable)#1 (1) { ["tabela"]=> array(2) { ["nome"]=> array(2) { [0]=> string(6) "fulano" [1]=> string(7) "ciclano" } ["idade"]=> array(2) { [0]=> string(2) "20" [1]=> string(2) "30" } } }
But then I add echo "--- " . $dt1::getTabela()['nome'][0];
It doesn't even print the ---. var_dump($dt1::getTabela()) and var_dump($dt1->getTabela()) also is blank. What is being missed here? Tried also this but didn't work.
You shouldn't use $this in a static function / for static properties as there is not necessarily an object context to use.
Instead, you should use self::$tabela everywhere instead.
Or change your variable (and the related methods...) to a "normal" protected property:
protected $tabela;
You are mixing static variables with non static accesors
i just put your code and i got a lot of errors/notices
NOTICE Accessing static property DataTable::$tabela as non static on line number 10
NOTICE Accessing static property DataTable::$tabela as non static on line number 31
NOTICE Accessing static property DataTable::$tabela as non static on line number 31
NOTICE Accessing static property DataTable::$tabela as non static on line number 31
NOTICE Accessing static property DataTable::$tabela as non static on line number 31
object(DataTable)#1 (1) { ["tabela"]=> array(2) { ["name"]=> array(2) { [0]=> string(7) "someone" [1]=> string(14) "another person" } ["age"]=> array(2) { [0]=> string(2) "20" [1]=> string(2) "30" } } }
FATAL ERROR Uncaught Error: Using $this when not in object context in /home/phptest/public_html/code.php70(5) : eval()'d code:20 Stack trace: #0 /home/phptest/public_html/code.php70(5) : eval()'d code(44): DataTable::getTabela() #1 /home/phptest/public_html/code.php70(5): eval() #2 {main} thrown on line number 20
Related
I really confused with the situation. I want to get data from function in my class, that created by ActiveRecord Model. Here a class:
class Bag extends ActiveRecord\Model {
static $table_name = "bags";
static $primary_key = 'bag_id';
public function get_pocket_types() {
$arr = json_decode($this->pocket_types);
return $arr;
}
}
I call it in my main code:
$bag = Bag::find_by_bag_id((int)$_GET['id']);
$types = $bag->get_pocket_types();
It seems to be good, but I have an error Notice: Undefined property: Bag::$pocket_types in models/Bag.php on line 21 when I try to get $this->pocket_types. This field is absolutely exists, like a field bag_id.
I've even tried to debug it (in function get_pocket_types() ):
echo $this->bag_id;
// OK
echo $this->bag_id_NOT_EXISTS;
// Fatal error: Uncaught exception 'ActiveRecord\UndefinedPropertyException' with message 'Undefined property: Bag->bag_id_NOT_EXISTS
// This is just for catch an error of REALLY not existed field
echo $this->pocket_types;
// Notice: Undefined property: Bag::$pocket_types in models/Bag.php on line 21
I called var_dump($this); in the function:
object(Bag)#16 (6) { ["errors"]=> NULL
["attributes":"ActiveRecord\Model":private]=> array(2) {
["bag_id"]=>
int(160)
["pocket_types"]=>
string(0) "" } ["__dirty":"ActiveRecord\Model":private]=> array(0) { } ["__readonly":"ActiveRecord\Model":private]=>
bool(false) ["__relationships":"ActiveRecord\Model":private]=>
array(0) { } ["__new_record":"ActiveRecord\Model":private]=>
bool(false) }
Somebody can explain what happens please?
Looks like you have created a custom getter with the same name as an attribute.
In which case you will need $this->read_attribute('pocket_types') instead of $this->pocket_types
Or, rename get_pocket_types to something like get_json_decoded_pocket_types.
What i have learned about objects in php is that the hash with a number (#n) points to the instantiation times for example :
if we have something like this object(Index)#5 (1) means that we have 5 instances of the Index object.
However in my case i'm working on a custom PHP MVC i have only instantiated the class once (i'm sure only once. a model class directly within the controller ) but i'm getting an object like so
object(Timino\App\Models\Index)#5 (1)
so why is this happening ?
do namespaces affect this ! ?
does this have an affection to the performance ?!
Namespaces should not affect this. For performance issues, the number of objects during script runtime will only have an impact, if the script is getting close or over the max memory limit. FYI, here are some considerations about performance.
A simple example to show/explain the "object counter":
class TestClass {
public $number = 2;
}
class ClassInner {
protected $number = 5;
protected $innerObject;
public function __construct() {
$this->innerObject = new \stdClass();
}
}
$testInstance = new TestClass();
$classInner = new ClassInner();
$classInner2 = new ClassInner();
$testInstance2 = new TestClass();
$classInner3 = $classInner2;
echo '<pre>';
var_dump($testInstance);
var_dump($classInner);
var_dump($classInner2);
var_dump($testInstance2);
var_dump($classInner3);
echo '</pre>';
Should result in this output. Pleas have a look at the order of instances and count:
object(TestClass)#1 (1) {
["number"]=>
int(2)
}
object(ClassInner)#2 (2) {
["number":protected]=>
int(5)
["innerObject":protected]=>
object(stdClass)#3 (0) {
}
}
object(ClassInner)#4 (2) {
["number":protected]=>
int(5)
["innerObject":protected]=>
object(stdClass)#5 (0) {
}
}
object(TestClass)#6 (1) {
["number"]=>
int(2)
}
object(ClassInner)#4 (2) {
["number":protected]=>
int(5)
["innerObject":protected]=>
object(stdClass)#5 (0) {
}
}
We use Payone with our Magento shop. And we want to show our users warnings in their cart when their total amount is too large for a certain payment method.
That is why I want to check the total amount against each payment method max order value.
But somehow I can not reach the correct data.
When I try to get them by Payones config:
$methods = Mage::helper('payone_core/config')->getConfigPayment($store);
I get an object->array with all methods, but they are protected. So I can not use them in my cart module.
What is a clean way to get Payones payment methods (all active methods with their max_order_value)?
Edit:
I tried following code, but it still says:
Fatal error: Cannot access protected property
Payone_Core_Model_Config_Payment::$methods in
/pathToClass/CtaB2c/Helper/Data.php on line 20
class CtaB2c_Helper_Data extends Payone_Core_Helper_Config {
public function getConfigPayment($store) {
return parent::getConfigPayment($store);
}
public function showPaymentRestrictions() {
$quote = Mage::getSingleton('checkout/session')->getQuote();
$store = $quote->getStoreId();
$total = $quote->getBaseGrandTotal();
$methods = $this->getConfigPayment($store);
$methods = $methods->methods; //error occurs here: member has protected access
$avaibleMethods = array();
foreach ($methods AS $mid => $method) {
$minTotal = $method->minOrderTotal;
$maxTotal = $method->maxOrderTotal;
if($minTotal <= $total && $maxTotal >= $total) {
$avaibleMethods[$mid] = $method->code;
}
}
return $avaibleMethods;
}
}
I know, there is no check if this payment method is avaible, but actually I just want know if maxOrderTotal is bigger than payment methods max_order_total. And of course I do not need this extra function. I could call parent::getConfigPayment($store) in my function as well.
Edit 2
This is the object I get from getConfigPayment():
object(Payone_Core_Model_Config_Payment)#<a number> (1) {
["methods":protected]=>
array(6) {
[<a number>]=>
object(Payone_Core_Model_Config_Payment_Method)#<a number> (38) {
["id":protected]=>
string(1) "a number"
["scope":protected]=>
string(6) "stores"
["scope_id":protected]=>
string(1) "<a number>"
["code":protected]=>
string(15) "advance_payment"
["name":protected]=>
string(8) "Vorkasse"
["sort_order":protected]=>
string(1) "<a number>"
["enabled":protected]=>
string(1) "<a number>"
["fee_config":protected]=>
NULL
["mode":protected]=>
string(4) "test"
["use_global":protected]=>
string(1) "1"
["mid":protected]=>
string(5) "<a number>"
["portalid":protected]=>
string(7) "<a number>"
["aid":protected]=>
string(5) "<a number>"
["key":protected]=>
string(16) "<a key>"
["allowspecific":protected]=>
string(1) "0"
["specificcountry":protected]=>
array(0) {
}
["allowedCountries":protected]=>
array(2) {
[0]=>
string(2) "DE"
[1]=>
string(2) "AT"
}
["request_type":protected]=>
string(16) "preauthorization"
["invoice_transmit":protected]=>
string(1) "0"
["types":protected]=>
NULL
["klarna_config":protected]=>
NULL
["klarna_campaign_code":protected]=>
NULL
["paypal_express_image":protected]=>
NULL
["check_cvc":protected]=>
NULL
["check_bankaccount":protected]=>
NULL
["bankaccountcheck_type":protected]=>
NULL
["message_response_blocked":protected]=>
NULL
["sepa_country":protected]=>
NULL
["sepa_de_show_bank_data":protected]=>
NULL
["sepa_mandate_enabled":protected]=>
NULL
["sepa_mandate_download_enabled":protected]=>
NULL
["customer_form_data_save":protected]=>
NULL
["is_deleted":protected]=>
string(1) "0"
["minValidityPeriod":protected]=>
string(0) ""
["minOrderTotal":protected]=>
string(1) "1"
["maxOrderTotal":protected]=>
string(4) "1000"
["parent":protected]=>
string(1) "<a number>"
["currency_convert":protected]=>
string(1) "0"
}
You can always extend the payone_core/config class YourNameSpace_Module_Helper_Payone extends ThePayOneNamespace_Payone_Core_Config and basically get any method to be public
class YourNameSpace_Module_Helper_Payone extends ThePayOneNamespace_Payone_Core_Config
public function someProtectedParentMethod()
{
return parent::someProtectedParentMethod();
}
}
The above will allow you to use any protected method and get the data you are after.
This is hopefully the Magento way to get information about Payones Payment methods. You should call setPaymentRestrictionNoticeMessage() somewhere in your controller.
class YourModule_Helper_Data extends Mage_Core_Helper_Abstract {
/**
* Returns array of methods that will not work with current max order value.
* #return array
*/
public function getPaymentsWithRestrictions() {
$quote = Mage::getSingleton('checkout/session')->getQuote();
$store = $quote->getStoreId();
$total = $quote->getBaseGrandTotal();
/**
* #var Payone_Core_Model_Config_Payment $model
*/
$model = Mage::helper('payone_core/config')->getConfigPayment($store);
$methods = $model->getMethods();
$restrictedMethods = array();
foreach ($methods AS $mid => $method) {
/**
* #var Payone_Core_Model_Config_Payment_Method $method
*/
$minTotal = $method->getMinOrderTotal();
$maxTotal = $method->getMaxOrderTotal();
$isEnabled = $method->getEnabled();
if($isEnabled && ($minTotal > $total || $maxTotal < $total)) {
$restrictedMethods[$mid] = $method;
}
}
return $restrictedMethods;
}
/**
* Sets notification message with information about payment methods
* that will not work.
*/
public function setPaymentRestrictionNoticeMessage() {
$restrictedMethodModels = $this->getPaymentsWithRestrictions();
$restrictedMethods = array();
foreach ($restrictedMethodModels AS $methodModel) {
/**
* #var Payone_Core_Model_Config_Payment_Method $methodModel
*/
$restrictedMethods[] = $methodModel->getName();
}
Mage::getSingleton('core/session')->addNotice(
Mage::helper('checkout')->__(
'Your order value is too high for following payment methods: ' . implode(', ', $restrictedMethods)
)
);
}
}
Get the Payone config in your function:
$payoneConfig = Mage::helper('payone_core/config')->getConfigPayment($storeId);
In Payone_Core_Model_Config_Payment you can find all methods which you can call on $payoneConfig, e.g. getAvailableMethods(). Overwrite Payone_Core_Model_Config_Payment the Magento way if you want to add more functionality.
Let's say I have a function which returns an object with one of it's parameters set to some certain value:
public function search($jobsdone, $date)
{
foreach ($jobsdone as $jd) {
if ($jd->date_worked == $date) return $jd;
}
}
Printing search($jobsdone, $key) yields such results:
object(JobDone)#378 (19) {
...
["attributes":protected]=>
array(9) {
["id"]=>
int(3593)
["user_id"]=>
int(13)
["object_id"]=>
int(99)
["job_id"]=>
int(130)
["date_worked"]=>
string(10) "2013-10-01"
["min_from"]=>
int(780)
["min_to"]=>
int(1080)
}
...
}
However, if I want to print out search($jobsdone, $key)->id, all I get is an error message of:
Trying to get property of non-object
What could I be missing here?
Your search function doesn't always return an object. Therefore, you get error Trying to get property of non-object whenever your search couldn't find a $jobdone object.
I am trying to find a way to get the source code for (user defined) PHP functions in a string.
For normal code this is easy, using reflection I can find the file and line numbers where the function is defined; then I can open the file and read the function source code.
This will not work if a function is defined in eval'd code. I do not want to keep record of all eval'd code.
Is this possible? If yes, then how?
Example code:
function myfunction() {
echo "Test";
}
eval('
function myevalfunction() {
echo "Test";
}
');
$a = new ReflectionFunction('myfunction');
echo $a;
$b = new ReflectionFunction('myevalfunction');
echo $b;
Output:
Function [ <user> <visibility error> function myfunction ] {
## test.php 3 - 5
}
Function [ <user> <visibility error> function myevalfunction ] {
## test.php(11) : eval()'d code 2 - 4
}
How about you define your own eval-function, and do the tracking there?
function myeval($code) {
my_eval_tracking($code, ...); # use traceback to get more info if necessary
# (...)
return eval($code);
}
That said, I do share a lot of Kent Fredric's feelings on eval in this case.
You cant just search through the files yourself? grep or wingrep is perfect for this.
If not you can try the pecl function rename_function and log all the eval calls which create functions.
My initial response is to say there's virtually 0 good reason to create a function in eval.
You can create functions conditionally, ie:
if ( $cond ){
function foo(){
}
}
If you want closure like behaviour I guess eval is the only way to do it until PHP5.3, but its EPIC bad stuff and you should avoid it all cost.
Here is why:
01 <?php
02
03 function foo ()
04 {
05 eval( '
06 function baz()
07 {
08 eval("throw new Exception();");
09 }
10 ');
11 baz();
12 }
13
14
15
16 try{
17 foo();
18 }catch( Exception $e ){
19 var_dump($e);
20 }
21 try{
22 foo();
23 }
24 catch( Exception $e ){
25 var_dump($e);
26 }
Which Emits this:
object(Exception)#1 (6) {
["message:protected"]=>
string(0) ""
["string:private"]=>
string(0) ""
["code:protected"]=>
int(0)
["file:protected"]=>
string(50) "/tmp/xx.php(10) : eval()'d code(4) : eval()'d code"
["line:protected"]=>
int(1)
["trace:private"]=>
array(3) {
[0]=>
array(3) {
["file"]=>
string(31) "/tmp/xx.php(10) : eval()'d code"
["line"]=>
int(4)
["function"]=>
string(4) "eval"
}
[1]=>
array(4) {
["file"]=>
string(11) "/tmp/xx.php"
["line"]=>
int(11)
["function"]=>
string(3) "baz"
["args"]=>
array(0) {
}
}
[2]=>
array(4) {
["file"]=>
string(11) "/tmp/xx.php"
["line"]=>
int(17)
["function"]=>
string(3) "foo"
["args"]=>
array(0) {
}
}
}
}
Fatal error: Cannot redeclare baz() (previously declared in /tmp/xx.php(10) : eval()'d code:2) in /tmp/xx.php(10) : eval()'d code on line 5
Call Stack:
0.0002 115672 1. {main}() /tmp/xx.php:0
0.0006 122304 2. foo() /tmp/xx.php:22
So much badness, so little effort.
If you want to find the source code, even in a debugger, you can define your own eval() function which works with temporary files:
function my_eval($code) {
$file = << TEMP-DIR >> . '/' . md5($code) . '.php';
if (!file_exists($file)) {
file_put_contents($file, "<?php\n" . $code);
}
return require($file);
}
In fact, I think that if you call this function eval and put it in the default namespace, most eval() calls in the code will call this function instead.