PHP error syntax error, unexpected T_FUNCTION in - php

/CustomPostType.php on line 165
// Initialise class variables as blank
$metaKeys = $this->get_meta_keys();
foreach( $metaKeys as $key )
if( !empty( $key ) )
$this->$key = null;
$this->ID = null;
The below code is what fixed the syntax error.
public function get_meta_keys( $objectName) {
$getClassVars = get_class_vars( $objectName );
return array_keys( $getClassVars);
}

There is syntax error in the code. It should be like this :
public function get_meta_keys( $objectName) {
$getClassVars = get_class_vars( $objectName );
return array_keys( $getClassVars);
}
Point to correct :
Correct function signature. Add argument in the function get_meta_keys().

Err, your code doesn't even look like it validates to me.
public function get_meta_keys( $objectName ) {
$getClassVars = get_class_vars( $objectName );
return array_keys( $getClassVars() );
}

Put semicolon at the end of the function call and also you need to format your code first.
public function get_meta_keys( )
{
$getClassVars = get_class_vars( $objectName );
return array_keys( $getClassVars() );
}

Related

Reference an object property with a variable

I need to reference an object property with a variable like this:
$user = User::find( 1 );
$mobile = $user->getData( 'phone.mobile' );
The value of the $data property in the object is a jSON array. Right now my user class looks like this:
class User extends Authenticable {
protected $fillable = [
'email',
'password',
'data',
'token',
];
protected $casts = [
'data' => 'array',
];
public function getData( $key = null ){
if( $key == null ){
// Return the entire data array if no key given
return $this->data;
}
else{
$arr_string = 'data';
$arr_key = explode( '.', $key );
foreach( $arr_key as $i => $index ){
$arr_string = $arr_string . "['" . $index . "']";
}
if( isset( $this->$arr_string ) ){
return $this->$arr_string;
}
}
return '';
}
}
The code above, always returns '', but $this->data['phone']['mobile'] returns the actual value stored in the database.
I guess I am referencing the key in a wrong way, can someone point me to the right way to access the value, given the string 'phone.mobile'
Laravel actually has a built-in helper function for the exact thing you're trying to do called array_get:
public function getData( $key = null )
{
if ($key === null) {
return $this->data;
}
return array_get($this->data, $key);
}
See documentation for more information: https://laravel.com/docs/5.5/helpers#method-array-get

PrestaShop backend, Fatal error in ajax call

On the backend of a PrestaShop site I'm using this function:
public function hookAjax($action, $id_product, $id_lang, $title, $descript, $order, $id = NULL)
{
/* various code*/
$this->context->smarty->assign(
array(
'block_define' => $this->getFormDesc($id_product)
)
);
return $this->context->smarty->fetch($this->local_path.'views/templates/hook/admin_extra_desc.tpl');
}
public function getFormDesc($id_product) {
$array = array();
foreach (Language::getLanguages() as $lang) {
/*various code*/
foreach($result as $k=> $r) {
$files = array();
$helper = new HelperImageUploader();
$helper->setMultiple(false)->setUseAjax(true)->setName('thumbnail_'.$r['id'].'_'.$r['id_lang'])->setFiles($files)->setMaxFiles(3)->setUrl('../modules/module-name/imgAjaxCall.php?');
$result[$k]['img-form'] = $helper->render();
$result[$k]['img'] = $result[$k]['img'] ? _PS_BASE_URL_.__PS_BASE_URI__.'modules/module-name/upload/'.$result[$k]['img'] : '';
}
$array[$lang["id_lang"]] = array(
'lang_data' => $lang,
'count' => count($result),
'data' => $result
);
}
return $array;
}
HookAjax is called by:
<?php
include(dirname(__FILE__).'/../../config/config.inc.php');
$context = Context::getContext();
$addDesc = Module::getInstanceByName('module-name');
echo $addDesc->hookAjax($_POST['action'],$_POST['id_prodotto'],$_POST['lang'],$_POST['title'], $_POST['text_desc'], NULL, $_POST['row']);
?>
But I struggle with this error:
Fatal error: Call to a member function addJs() on a non-object in {my_site}/classes/helper/HelperUploader.php on line 257
You need to include init.php in HookAjax after including config.inc.php so that controller is initialized in context.
include(dirname(__FILE__).'/../../init.php');
Note that this is just bad practice, respect the MVC and use proper controllers for your AJAX calls and data validation/processing in them, not inside main module class.

Laravel : Can't use `Input::get('foobar')` as an action's default parameter value

I'm trying to do the following in my controller:
public function moveMessagesToArchive( $message_ids = Input::get('message_ids') )
{
$json = json_encode( $message_ids);
echo $json;
}
And it keeps throwing the following error:
syntax error, unexpected '(', expecting ')'
at the function signature. What's causing the problem here?
Update
While, I wait for the reason I've written the following work around:
public function moveMessagesToArchive( $message_ids = array() )
{
$ids = array();
if ( ( count($message_ids) !== 0 ) && is_array($message_ids) ) {
$ids = $message_ids;
} else if ( Input::get('message_ids') ) {
$ids = Input::get('message_ids');
} else {
return false;
}
$json = json_encode( $ids );
echo $json;
}
It is not possible in PHP. According to the documentation
The default value must be a constant expression, not (for example) a variable, a class member or a function call.
Reference Example 4
What you are trying to do is not, and never has been supported by php.
Nothing at all to do with Laravel.

Object could not be converted into string

code:
public function atualizarPorLocal( $acao, $novasRedes )
{
$em = $this->getEntityManager();
$apagaObj = $em->getRepository( 'CommonBundle:AcaoRede' )->findBy( array( 'acao'=>$acao ) );
foreach ( $apagaObj as $acao){
if (!empty($acao))
$em->remove($acao);
}
$em->flush();
foreach ( $novasRedes as $idRede )
{
$new = new AcaoRede();
$new->setAcao( $em->getRepository( 'CommonBundle:Acao' )->find( $acao ) );
$new->setRede( $em->getRepository( 'CommonBundle:Rede' )->find( $idRede ) );
$em->persist( $new );
}
$em->flush();
}
erro:
PHP Catchable fatal error: Object of class \CommonBundle\Entity\AcaoRede could not be converted to string in vendor/doctrine/orm/lib/Doctrine/ORM/UnitOfWork.php on line 2794, referer: /app_dev.php/modulo/editar/col_soft
what can I do to work around this error?
You have to use Acao's id
$new->setAcao( $em->getRepository( 'CommonBundle:Acao' )->find( $acao->getId() ) );
Doctrine's find method is expecting id field, so it tries to convert your $acao to string using __toString() method. You have to pass $acao->getId() to make it work
variable $acao was assuming a different value when entered in the second foreach
solved this problem by changing the name of the variable.
foreach ( $apagaObj as $acaoObj){
if (!empty($acaoObj))
$em->remove($acaoObj);
}

PHP Immutable Object Efficiencies

I've been working on an immutable object for use in PHP. One can do this by adapting a singleton pattern and playing around with the magic methods easily enough, but I have a couple of specific needs here.
1. Under no circumstances is a reference to a contained value to be returned.
2. If the contained data is an array (most likely a big 'ol tree loaded form json_decode()), then one must be able to search for a key using a search string
e.g.:
$thing = $foo->get( 'go.get.the.thingy.at.this.level' );
...which would return:
$foo->_data['go']['get']['the']['thingy']['at']['this']['level']
3. When walking down a contained array looking for keys, references are used -- and not copies.
This means that I will want to avoid the use of a foreach() call if it at all possible. If you don't understand what I mean (or understand why this is a concern), in PHP:
foreach() does not work on the object you are iterating.
foreach() works on a copy of the object being iterated.
My Question
I've got something of a shell here (minor syntax problems aside), but I'd like to see if this can be made any more efficient, or if there are better tricks at accomplishing the same task
class ProperlyProtectedObject {
// PUBLIC STUFF
/// Initializes the singelton and returns a reference -- or cowardly returns a null.
public static function init( $value ) {
if( true === empty( self::$_self ) ) { // empty returns true if 0, false, null, or not set
if( false === isset( $value ) ) { // isset returns true if not set or null.
return null; // ...you idjit!
}
self::$_data = new ProperlyProtectedObject( $value );
}
return & self::$_self;
}
/// invoke ( php > =5.3 ): default
public function __invoke( $var ) {
return $this->get( $var );
}
public function __call( $f, $args ) {
return $this->get( $args );
}
public function __callStatic( $f, $args ) {
return null; // idjit.
}
/// get: NEAT TRICK:
/// if you know that you are storing an array here, then you can pass a dot syntax
/// string (e.g.: foo.bar.soemthing_else.foo.0 ) and
/// -- provided that your keys don't contain dots (:-P) --you can get the value of a
/// nested array key!
/// \return <Mixed> Any value **except** NULL is the value at the depth you are looking for.
/// \return NULL this means that you.have.a.BAD.Key.string.SomeWhere
public function get( $val ) {
$copyOfThing = null;
if( true === is_array( self::$_data ) ) {
if( true === is_string( $val ) ) {
$keys = explode( '.', $val );
if( 0 < count( $keys ) {
$copyOfThing = walk( self::$_data, $keys );
}
}
}
else {
$copyOfThing = self::$_data;
}
return $copyOfThing;
}
/// set: DOES NOTHING. This object is meant to take an act of congress to delete data.
public function __set( $objProp, $value ) {
// do nothing.
// echo '<pre>DIE IN A FIRE!!!! ' . var_export( $objProp, true ) . '</pre>';
}
/// isset:
public function __isset( $objProp ) {
return ( null !== $this->get( $objProp ) ) ? true : false;
}
/// unset: DOES NOTHING.This object is meant to take an act of congress to delete data
public function __unset( $objProp ) {
// do nothing.
// echo '<pre>DIE IN A FIRE!!!! ' . var_export( $objProp, true ) . '</pre>';
}
//
// PRIVATE STUFF
//
private $_self; ///< the singleton instance
private $_data = Array(); ///< this is the data. Just the data, and only the data.
/// CTOR: Singleton!
private function __construct( $value ) {
self::$_data = $value;
}
/// CCTOR: Singletons have have no need to copy themselves
private function __clone() {
// do nothing
}
/// fetches the value from WAAAY down in the array
private function walk( Array &$arr, Array $keystack ) {
$key = array_pop( $keystack );
if( false === array_key_exists( $key, $arr ) ) {
return null;
}
if( 0 count( $keystack ) ) {
return $arr[$key];
}
else {
return walk( $arr[$key], $keystack );
}
}
}

Categories