Send array to class php

PHP how to send array variables to Class function

Sorry that it took so long to answer, I totally forgot your question. Well, lets take a look at your problem, hope to solve it.

I try to explain it as good as I can, so that you understand whats going on. First of all, lets look at your error message

Fatal error: Call to a member function insert() on array in E:\Xampp\htdocs\php\bazy_danych\obiektowe\my\register.php on line 78

Okay. Call to a function on array. lets have a look at how you actually call the function:

$rejestruj = new Dbinsert(); $filtruj = $rejestruj->regFilter(); var_dump($filtruj); $dodaj = $filtruj->insert(); 

And exactly here is your error. You have to understand that you call methods on objects and pass your data to this methods, not to call the methods on your data. What do I mean with that?

$rejestruj is your Dbinsert object. You create it in your first line of code here. Then, you call the regFilter function on it. Still anything is fine. As you see, var_dump gives you the expected results. So the error has to be on your last lane of code. And indeed, you try to call the method insert() on your array. And that won’t work, since your array don’t know any method called insert() .

The right call to the method would be (Not the final one. ):

Now the method call should work. But in fact, it won’t insert anything. Why? Because your insert() method try to bind the variables $login and $haslo — two variables the method don’t know. So we need to pass the data in your method. To do that, you have to do the following changes:

Method call:

$rejestruj->insert($filtruj); // $filtruj contains your array

And your Dbinsert should look like:

class Dbinsert extends Dbconnect< protected $query; protected $dbo; public function insert($data)< $this->connect(); $this->query = "INSERT INTO uzytkownik (id, nazwa, haslo) VALUES ('', :login, OLD_PASSWORD(:haslo))"; if(!$result = $this->connect()->prepare($this->query)) < echo 'Zapytanie nie powiodło się'; >else < $result->bindParam(':login', $data["login"]); $result->bindParam(':haslo', $data["haslo"]); $result->execute(); > $dbo = null; > > 

I hope your code works with this changes. So, while in my opinion the code should work now, I want to mention that there are many things you could improve. For example, you’re not programming real «object-oriented» . its more some pseudo OOP you’re writing here. Some things are quite bad practice (could be done much easier). I don’t want to dive to deep into details, since I don’t know if you’re interested in it. If you wish I can give you some more advises, but only if you wish.

Otherwise I really hope my answer help you. If the whole thing still doesn’t work, please let me know so I can look at it again.

Since it seems I haven’t been clear enough, here the code how it should look like now:

$rejestruj = new Dbinsert(); $filtruj = $rejestruj->regFilter(); $dodaj = $rejestruj->insert($filtruj); 

More Answer

  • How to run a function in a PHP Class from Command Line (Symfony)
  • How to Output Array from Recursive PHP 7 Function without Array to String Error
  • How do I tell a variable to be a specific custom type for a class function in PHP
  • How to use array values as Variables in big multidimensional Array php
  • How do I pass multiple variables to function within PHP statement?
  • How to send SMS to a PHP array with Twilio API
  • How do I pass objects into an array via getters/setters across another class in PHP OOP?
  • How to assign the values of one array to the variables in a different array in PHP
  • How to access the config php values (multidimensional array) to class function in PHP
  • how can pass function as argument php class
  • How to set and pass associative array in a php function
  • How to set variable in PHP class function
  • How to add full html code into an PHP array and echo the array with array_rand function
  • how to read data from variables using header function in php
  • How to PHP Unit Test a function that calls an external class with a private constructor
  • PHP calling class function dynamically by variables caughts exception
  • How to check if variables from the array are between the range of 0 and 101? php
  • How can I make variables accessible to all the functions within the class in php
  • How do I write this php array function in JS/jQuery?
  • How to send data in 2 dimensional array with ajax to the php page and print each dimension separately?
  • How to use variables from another php file to include in a html page javascript function
  • How is the current function converting an object to an array in PHP
  • Php — how to encode an array as json and send it back
  • how to use 2 variables as function name in PHP
  • How to execute a function after response send in PHP
  • how do i send javascript variables to PHP and return the results
  • How to pass different variables to jQuery function from php
  • How to pass PHP variables to a function
  • PHP — How to assign object variables to function variables automatically?
  • How to correctly send php variables through ng-click parameters
  • how to turn associative array into function parameters in php
  • Pass variables to a PHP Class Constructor through a class’s function
  • How to call a specific php function inside a class through ajax?
  • How to send array using base64 in PHP and cURL?
  • How to send an array with jquery to php script?
  • How to send array js array to php page in ajax request
  • PHP passing variables vs array into function
  • How to send an empty array to PHP server using Javascript
  • How to send JSON encoded PHP array to datatables on same page
  • how to globalize php getimagesize function variables
  • How can I late static binding in inherited class with variable variables of PHP
  • How to find php files with code outside of a function or class and doesn’t contain a string?
  • How to send JSON POST requests in PHP using variables from another POST requests?
  • how to convert strings to array in php without using explode function
  • How to pass an array index in a function & check in a function either this index is set or not php
  • PHP Function not functioning correctly with array when variables are in a different order
  • How to do jquery autocomplete function from a php variable array
  • passing variables from a protected function to a public function inside the same class in php
  • How to send an array to php and load again in html?
  • How to pass php id from array to a javascript function
Читайте также:  Javascript clear form input

More answer with same ag

  • PHP Zend Compare form field value with constant
  • PHP image cropping: blurry result
  • php find one array values to another multidimensional array and if value not preset set zero
  • Undefined index error in php (dropdown filters do not work)
  • How to put symbols ‘?’ and ‘=’ into url from variable?
  • javascript php AJAX refresh part of a DIV
  • How to show dropdown list in YII1 with condition?
  • Is there a way to combine angular with existing php/js/html web project?
  • CakePHP 3: saving hasOne association ($_accessible not set)
  • CakePhp: How to display specific enum values from a list of multiple ones
  • Chrome extension cause PHP server to send HTTP 500 error?
  • Preventing easily downloadable videos
  • Send «AdminMessage» using PHP on GAE?
  • php error with completely wrong, not even possible filepath
  • How to set_include_path in php (Dreamweaver)?
  • PHP LDAP Connection to Authenticate against Active Directory from External Server
  • Form not Cleared on Submit
  • ZK Teco Finger Print PHP
  • Overwrite form mapper field options
  • Creating formula
  • Can not use format_datetime() for french with Symfony 5.2 PHP 8
  • PHP/prestashop: strange HTML/XML error displayed in the browser
  • Remove enumeration item from array PHP
  • Ajax does not pass data to my controller
  • Old php site not working on new IIS server, need to use GD library but can’t figure it out
  • How do I programatically search Google Plus for posts via the PHP library
  • cakephp 3 sort by deeply associated table
  • PHP header not prompting download
  • Contactform.php not sending all inputs
  • Passing data to another domain upon Ajax success
  • login.php, retrieving and matching password not work
  • Understanding ssssii in line 32
  • text watermark in php
  • Use Assetic with BootstrapBundle
  • codeigniter not loading application/core files
  • is there a change that if maximum session capacity is over, the site will get logged out?
  • How to register helper function in lightncandy handlebar
  • xml parsing xpath error using php
  • sending email to multiple recipients not see other users addresses
  • appending variable’s while using exec()
  • How to calculate date and time difference?
  • Prevent page refreshes updating a table in PHP — via link and not a form
  • PHP Associative Array Quotations
  • javascript if checkbox is checked, href to ?page2, if at ?page2: keep cb checked, when unchecked, href to ?page1
  • Cleaning up code for a custom exception class in PHP
  • Upload file using HTTP. getting error :- HttpSendReuest 12005
  • PDO __constructs expects at least 1 parameter, 0 given
  • getting cookie from an external javascript in php before generating HTML output
  • Define variables in a template
  • Tagging composer package updates
Читайте также:  Random functions in java

Источник

Convert an Array To StdClass With PHP

For more details, click on this link. To Convert an Array to stdClass with PHP is an easy step. In this tutorial, we will use different ways using which we can easily achieve the desired outcome. Before jumping right into the solution, let’s understand a few things about stdClass is in PHP.

What is stdClass in PHP?

stdClass is just a generic empty class in PHP OR we can say it’s PHP’s class prototype like Object.prototype in JavaScript, Object in Java OR object in Python. Here, point to be noted that despite generic class, stdClass is NOT the base class for objects in PHP and we can prove this using instanceof keyword.

 class nature<> $objNature= new nature(); if ($objNature instanceof stdClass) echo 'Yes'; > else  echo 'No'; > 

Solution 1: Using typecast/ Type Juggling

Typecasting an array to a stdClass object is the easiest way to achieve. It will convert value of one data type into another data type.

 $empInfo = array( 'name'=>'John', 'address'=>'Houston', ); $empInfoObj = (object) $empInfo; print_r($empInfoObj); 
// OUTPUT stdClass Object ( [name] => John [address] => Houston )

Here, we defined an array $empInfo in which we defined 3 keys and associated values and in the next line, we typecast our array into an object using the name of the desired type, written in parentheses before the variable which is to be cast.

We can now access the property of the object with object-oriented style syntax as $empInfoObj->name which will output John.

This is the simplest solution to our problem. But what if the array is multidimensional? Does the above solution work? And the answer is NO.

Let’s update our $empInfo array.

 $empInfo = array( 'name'=>'John', 'address'=>'Houston', 'employment' => array( 'id' => '1', 'address' => 'Los Angeles' ) ); $empInfoObj = (object) $empInfo; print_r($empInfoObj); 
// OUTPUT stdClass Object ( [name] => John [address] => Houston [employment] => Array ( [id] => 1 [address] => Los Angeles ) )

As we can see, an array defined inside the employment key does not get converted to a stdClass. So, type juggling casts the values at the opt level keys and not the keys which are defined in a nested pattern.

So, here we can write our customize function to solve the problem.

Solution 2: Using custom function

 function toObject($arr)  if (is_array($arr))  // Return object return (object) array_map('toObject', $arr); > return false; > $empInfo = array( 'name'=>'John', 'address'=>'Houston', 'employment' => array ( 'id' => '1', 'address' => 'Los Angeles' ) ); print_r(toObject($empInfo)); 
// OUTPUT stdClass Object ( [name] => John [address] => Houston [employment] => stdClass Object ( [id] => 1 [address] => Los Angeles ) )

Here, in the above example, we have recursively called toObject() function to check the innermost array present (if any) and then typecast it into an object.

Solution 3: Using json_encode() and json_decode()

json_encode() and json_decode() are the functions especially for performing operations on JSON string.

So, first, we’ll convert an object into a JSON string and then will convert it into an object using json_decode() .

 $empInfo = array( 'name'=>'John', 'address'=>'Houston', 'employment' => array( 'id' => '1', 'address' => 'Los Angeles' ) ); print_r(json_decode(json_encode($empInfo))); 
// OUTPUT stdClass Object ( [name] => John [address] => Houston [employment] => stdClass Object ( [id] => 1 [address] => Los Angeles ) )

Instead of writing a custom function, we can use these in-built functions to get the desired output and also we don’t need to worry about the innermost array element as these two functions will take care of them.

Conclusion:

These 3 ways of Converting an Array To StdClass With PHP gives better options depending upon the requirement. Mostly in today’s web frameworks we commonly deal with class hierarchy. So converting an array into stdClass at runtime will be a better option.

Источник

Оцените статью