Alternative to logicalNot() - not doing what expected - php
I made a query in a EntityRepository.php file, the query goes through and gives me a number of matching entities for example:
100
My new goal is to filter out all entities which have the property feedback.appointmentState.uid = 4.
and when I put in this following constraint:
$query->equals('feedback.appointmentState.uid', 4)
it gives me
0
Now comes the part that I don't understand -
When I change that part to:
$query->logicalNot($query->equals('feedback.appointmentState.uid', 4))
I get
90
It's not quite working this way since it should output 100 as there are no entities that match that filter - but how can I achieve this the best way?
For clarification here my code example (of course I didn't uncomment both commented parts at the same time)
public function countByCompany($company) {
$query = $this->createQuery();
$constraints[] = $query->equals('deleted', 0);
$constraints[] = $query->equals('hidden', 0);
$constraints[] = $query->equals('socialworker.company', $company);
$total = $query->matching($query->logicalAnd($constraints))->count();
// $total is 30
// $constraints[] = $query->equals('feedback.appointmentState.uid', 4);
// $totalCancelled = $query->matching($query->logicalAnd($constraints))->count();
// $totalCancelled is 0
// $constraints[] = $query->logicalNot($query->equals('feedback.appointmentState.uid', 4));
// $totalWithoutCancelled = $query->matching($query->logicalAnd($constraints))->count();
// $totalWithoutCancelled is 15
return false;
}
I dissolve your last query to
public function countByCompany($company) {
$query = $this->createQuery();
$totalWithoutCancelled = $query->matching(
$query->logicalAnd(
$query->equals('deleted', 0),
$query->equals('hidden', 0),
$query->equals('socialworker.company', $company),
$query->logicalNot(
$query->equals('feedback.appointmentState.uid', 4)
)
)
)->count();
return false;
}
Try mine. Does this the same?
public function countByCompany($company) {
$query = $this->createQuery();
$total = $query->matching(
$query->logicalAnd(
$query->equals('deleted', 0),
$query->equals('hidden', 0),
$query->equals('socialworker.company', $company)
),
$query->logicalNot(
$query->equals('feedback.appointmentState.uid', 4)
)
)->count();
return false;
}
Related
Sphinx Query is returning null results in PHP
I am currently using PHP to query from my sphinx index. The index is building properly, however the search is not. Originally I had my query set up like the following: private function _doMapSearchAll($textSearch, $typeFilterArr, $rads = array(), $centre = array(), $showFavourites = false) { // lookup the location based on the search and return the results in that // map bounds ignore for boundary searches $rsArr = array(); $skipDataSearch = false; if (!COUNT($rads)) { // handle airport code lookups if we have 3 characters if (strlen($textSearch) === 3) { $rsArr = $this->_doMapAirportSearch($textSearch); if (COUNT($rsArr)) { $skipDataSearch = true; } } // still no results based on the above search, do generic map search if ($skipDataSearch === false) { $rsArr = $this->_doMapGeoSearch($textSearch, $typeFilterArr, $centre); if (COUNT($rsArr['results']) > 0) { $skipDataSearch = false; } } } // if we are doing a boundary search, or we have no results from the above, // get all results based on our location if ($skipDataSearch === false) { // fall back onto searching via the data // normalise the search string $originalSearchString = $this->doNormalisation($textSearch); // use sphinx for the search $sphinx = $this->_getSphinxConnection(); $sphinx->setLimits(0, $this->container->getParameter('search_max_results'), $this->container->getParameter('search_max_results')); if (COUNT($typeFilterArr)) { $sphinx->SetFilter('fldSiteTypeUID_attr', $typeFilterArr); } // if we're doing a boundary search, skip the search string if (COUNT($rads) > 0) { $originalSearchString = ''; if ($showFavourites === false) { //$sphinx->SetFilterFloatRange('lat_radians', min($rads['minLat'], $rads['maxLat']), max($rads['minLat'], $rads['maxLat'])); //$sphinx->SetFilterFloatRange('long_radians', min($rads['minLon'], $rads['maxLon']), max($rads['minLon'], $rads['maxLon'])); if ($rads['minLat'] > $rads['maxLat']) { $rads['minLat'] = $rads['minLat'] - 360; } if ($rads['minLon'] > $rads['maxLon']) { $rads['minLon'] = $rads['minLon'] - 180; } $sphinx->SetFilterFloatRange('lat_radians', $rads['minLat'], $rads['maxLat']); $sphinx->SetFilterFloatRange('long_radians', $rads['minLon'], $rads['maxLon']); } } // order by centre point if (COUNT($centre) > 0) { // otherwise start in the centre $sphinx->SetGeoAnchor('lat_radians', 'long_radians', (float) $centre['centreLat'], (float) $centre['centreLon']); $lintDistanceLimit = 999999999.0; // everything if ($showFavourites === false && isset($rads['maxLat'])) { $radiusMiles = $this->get('geolocation_helper')->getSeparation( rad2deg($rads['maxLat']), rad2deg($rads['minLon']), rad2deg($rads['minLat']), rad2deg($rads['maxLon']), "M" ); $lintDistanceLimit = $radiusMiles * 1609; // miles to meters... } $sphinx->SetFilterFloatRange('geodist', 0.0, (float)$lintDistanceLimit); $sphinx->SetSortMode(SPH_SORT_EXTENDED, 'geodist ASC'); } else { // apply search weights $sphinx->SetFieldWeights(array('fldTown_str' => 100, 'fldAddress1_str' => 30, 'fldSiteName_str' => 20)); } // if we should be limiting to only favourites, pickup the selected // favourites from cookies if ($showFavourites === true) { $request = $this->container->get('request_stack')->getCurrentRequest(); $favourites = explode(',', $request->cookies->get('HSF_favlist')); if (count($favourites)) { foreach ($favourites as $k => $favourite) { $favourites[$k] = (int)$favourite; } $sphinx->SetFilter('fldUID_attr', $favourites); } } $rs = $sphinx->Query($originalSearchString, $this->container->getParameter('sphinx_index')); echo json_encode($sphinx); $rsArr['results'] = array(); if (isset($rs['matches']) && count($rs['matches'])) { // update the search text to what we actually searched for, this // is needed in case we've updated/set $rsArr['searchText'] // after a geolookup $rsArr['searchText'] = $textSearch; // clear any previous bounds set by the geolookup, we don't want this // if we have direct text match results $rsArr['geobounds'] = array(); if (isset($rs['matches']) && count($rs['matches'])) { foreach ($rs['matches'] as $k => $match) { $rsArr['results'][$k] = $this->_remapSphinxData($k, $match); } } // sort the results by distance usort($rsArr['results'], function ($a, $b) { return $a['fldDistance'] - $b['fldDistance']; }); } } // add on the total record count $rsArr['total'] = (int) COUNT($rsArr['results']); return $rsArr; } That was returning nothing and giving me the error for GEODIST(): {"_host":"sphinx","_port":36307,"_path":"","_socket":false,"_offset":0,"_limit":250,"_mode":0,"_weights":[],"_sort":4,"_sortby":"geodist ASC","_min_id":0,"_max_id":0,"_filters":[{"type":2,"attr":"geodist","exclude":false,"min":0,"max":999999999}],"_groupby":"","_groupfunc":0,"_groupsort":"#group desc","_groupdistinct":"","_maxmatches":"250","_cutoff":0,"_retrycount":0,"_retrydelay":0,"_anchor":{"attrlat":"lat_radians","attrlong":"long_radians","lat":0.9300859583877783,"long":-2.0943951023931953},"_indexweights":[],"_ranker":0,"_rankexpr":"","_maxquerytime":0,"_fieldweights":[],"_overrides":[],"_select":"*","_error":"searchd error: geoanchor is deprecated (and slow); use GEODIST() expression","_warning":"","_connerror":false,"_reqs":[],"_mbenc":"","_arrayresult":false,"_timeout":0}{"results":[],"bounds":{"bllat":53.395603,"trlat":53.7159857,"bllng":-113.7138017,"trlng":-113.2716433},"geocentre":{"lat":53.5461245,"lon":-113.4938229},"checksum":"204a43923452936b00a10c8e566c4a48d4fdb280f97fd4042646eb45c8257bbc","searchText":"Edmonton, AB, Canada","skipResults":true,"showFavourites":false} To fix this I changed the SetGeoAnchor function to the following: private function _doMapSearchAll($textSearch, $typeFilterArr, $rads = array(), $centre = array(), $showFavourites = false) { // lookup the location based on the search and return the results in that // map bounds ignore for boundary searches $rsArr = array(); $skipDataSearch = false; if (!COUNT($rads)) { // handle airport code lookups if we have 3 characters if (strlen($textSearch) === 3) { $rsArr = $this->_doMapAirportSearch($textSearch); if (COUNT($rsArr)) { $skipDataSearch = true; } } // still no results based on the above search, do generic map search if ($skipDataSearch === false) { $rsArr = $this->_doMapGeoSearch($textSearch, $typeFilterArr, $centre); if (COUNT($rsArr['results']) > 0) { $skipDataSearch = false; } } } // if we are doing a boundary search, or we have no results from the above, // get all results based on our location if ($skipDataSearch === false) { // fall back onto searching via the data // normalise the search string $originalSearchString = $this->doNormalisation($textSearch); // use sphinx for the search $sphinx = $this->_getSphinxConnection(); $sphinx->setLimits(0, $this->container->getParameter('search_max_results'), $this->container->getParameter('search_max_results')); if (COUNT($typeFilterArr)) { $sphinx->SetFilter('fldSiteTypeUID_attr', $typeFilterArr); } // if we're doing a boundary search, skip the search string if (COUNT($rads) > 0) { $originalSearchString = ''; if ($showFavourites === false) { //$sphinx->SetFilterFloatRange('lat_radians', min($rads['minLat'], $rads['maxLat']), max($rads['minLat'], $rads['maxLat'])); //$sphinx->SetFilterFloatRange('long_radians', min($rads['minLon'], $rads['maxLon']), max($rads['minLon'], $rads['maxLon'])); if ($rads['minLat'] > $rads['maxLat']) { $rads['minLat'] = $rads['minLat'] - 360; } if ($rads['minLon'] > $rads['maxLon']) { $rads['minLon'] = $rads['minLon'] - 180; } $sphinx->SetFilterFloatRange('lat_radians', $rads['minLat'], $rads['maxLat']); $sphinx->SetFilterFloatRange('long_radians', $rads['minLon'], $rads['maxLon']); } } // order by centre point if (COUNT($centre) > 0) { // otherwise start in the centre // $sphinx->SetGeoAnchor('lat_radians', 'long_radians', (float) $centre['centreLat'], (float) $centre['centreLon']); $centreLat = (float) $centre['centreLat']; $centreLon = (float) $centre['centreLon']; $sphinx->SetSelect("GEODIST(lat_radians, long_radians, $centreLat, $centreLon) AS geodist"); $lintDistanceLimit = 999999999.0; // everything if ($showFavourites === false && isset($rads['maxLat'])) { $radiusMiles = $this->get('geolocation_helper')->getSeparation( rad2deg($rads['maxLat']), rad2deg($rads['minLon']), rad2deg($rads['minLat']), rad2deg($rads['maxLon']), "M" ); $lintDistanceLimit = $radiusMiles * 1609; // miles to meters... } $sphinx->SetFilterFloatRange('geodist', 0.0, (float)$lintDistanceLimit); $sphinx->SetSortMode(SPH_SORT_EXTENDED, 'geodist ASC'); } else { // apply search weights $sphinx->SetFieldWeights(array('fldTown_str' => 100, 'fldAddress1_str' => 30, 'fldSiteName_str' => 20)); } // if we should be limiting to only favourites, pickup the selected // favourites from cookies if ($showFavourites === true) { $request = $this->container->get('request_stack')->getCurrentRequest(); $favourites = explode(',', $request->cookies->get('HSF_favlist')); if (count($favourites)) { foreach ($favourites as $k => $favourite) { $favourites[$k] = (int)$favourite; } $sphinx->SetFilter('fldUID_attr', $favourites); } } $rs = $sphinx->Query($originalSearchString, $this->container->getParameter('sphinx_index')); echo json_encode($sphinx); $rsArr['results'] = array(); if (isset($rs['matches']) && count($rs['matches'])) { // update the search text to what we actually searched for, this // is needed in case we've updated/set $rsArr['searchText'] // after a geolookup $rsArr['searchText'] = $textSearch; // clear any previous bounds set by the geolookup, we don't want this // if we have direct text match results $rsArr['geobounds'] = array(); if (isset($rs['matches']) && count($rs['matches'])) { foreach ($rs['matches'] as $k => $match) { $rsArr['results'][$k] = $this->_remapSphinxData($k, $match); } } // sort the results by distance usort($rsArr['results'], function ($a, $b) { return $a['fldDistance'] - $b['fldDistance']; }); } } // add on the total record count $rsArr['total'] = (int) COUNT($rsArr['results']); return $rsArr; } This gives me back results however they look like this: {"_host":"sphinx","_port":36307,"_path":"","_socket":false,"_offset":0,"_limit":250,"_mode":0,"_weights":[],"_sort":4,"_sortby":"geodist ASC","_min_id":0,"_max_id":0,"_filters":[{"type":2,"attr":"geodist","exclude":false,"min":0,"max":999999999}],"_groupby":"","_groupfunc":0,"_groupsort":"#group desc","_groupdistinct":"","_maxmatches":"250","_cutoff":0,"_retrycount":0,"_retrydelay":0,"_anchor":[],"_indexweights":[],"_ranker":0,"_rankexpr":"","_maxquerytime":0,"_fieldweights":[],"_overrides":[],"_select":"GEODIST(lat_radians, long_radians, 0.93008595838778, -2.0943951023932) AS geodist","_error":"","_warning":"","_connerror":false,"_reqs":[],"_mbenc":"","_arrayresult":false,"_timeout":0}{"results":[[null,null,null,null,null,null,null,"Other","http:\/\/localhost:8080\/themes\/docker\/images\/Site-Type-Other.png",null,34362776,null,""],[null,null,null,null,null,null,null,"Other","http:\/\/localhost:8080\/themes\/docker\/images\/Site-Type-Other.png",null,38279990,null,""],[null,null,null,null,null,null,null,"Other","http:\/\/localhost:8080\/themes\/docker\/images\/Site-Type-Other.png",null,7963188,null,""],[null,null,null,null,null,null,null,"Other","http:\/\/localhost:8080\/themes\/docker\/images\/Site-Type-Other.png",null,7971966,null,""],[null,null,null,null,null,null,null,"Other","http:\/\/localhost:8080\/themes\/docker\/images\/Site-Type-Other.png",null,31790051,null,""],[null,null,null,null,null,null,null,"Other","http:\/\/localhost:8080\/themes\/docker\/images\/Site-Type-Other.png",null,7972301,null,""],[null,null,null,null,null,null,null,"Other","http:\/\/localhost:8080\/themes\/docker\/images\/Site-Type-Other.png",null,33589292,null,""],[null,null,null,null,null,null,null,"Other","http:\/\/localhost:8080\/themes\/docker\/images\/Site-Type-Other.png",null,33589642,null,""],[null,null,null,null,null,null,null,"Other","http:\/\/localhost:8080\/themes\/docker\/images\/Site-Type-Other.png",null,7962913,null,""],[null,null,null,null,null,null,null,"Other","http:\/\/localhost:8080\/themes\/docker\/images\/Site-Type-Other.png",null,31789941,null,""],[null,null,null,null,null,null,null,"Other","http:\/\/localhost:8080\/themes\/docker\/images\/Site-Type-Other.png",null,7962178,null,""],[null,null,null,null,null,null,null,"Other","http:\/\/localhost:8080\/themes\/docker\/images\/Site-Type-Other.png",null,49484181,null,""],[null,null,null,null,null,null,null,"Other","http:\/\/localhost:8080\/themes\/docker\/images\/Site-Type-Other.png",null,31795436,null,""], ..... My searchd config looks like this: searchd { listen = 36307 listen = 9306:mysql41 log = /opt/sphinx/searchd.log query_log = /opt/sphinx/query.log read_timeout = 5 max_children = 30 pid_file = /opt/sphinx/searchd.pid seamless_rotate = 1 preopen_indexes = 1 unlink_old = 1 binlog_path = /opt/sphinx/ } I am new tp Sphinx and need help correcting this query. Any thoughts? Edit: This is sphinx version 3.4.1
So after hours on this over the past few days, I have found the answer...: I was missing the * in the statement: $sphinx->SetSelect("*, GEODIST($centreLat, $centreLon, lat_radians, long_radians) as geodist"); I hope this helps anyone who has this issue in the future
How to handle a Function utilizing a Stored Procedure from an array of data
I have created a function that checks for quantities before saving the data into the sales table. This function works well on Single variables and the moment the post variables become multiple; it doesn’t work because they become an array. Is there a way in which I can handle an array utilizing the idea behind this function? The idea is for every set say ($productCode = 2) & ($quantity = 10) function checks, then say ($productCode = 1) & ($quantity = 20) until the last set. <?php //Checking quantity availability //Post variables //$productCode=$_POST['productCode']; //$quantity=$_POST['quantity']; //Equivalent variables $productCode = array(2, 1, 7, 2); $quantity = array(10, 20, 30, 40); //My wild thought BUT no LUCK for ($i = 0; $i < count($productCode); $i++) { $productCode=$productCode[$i]; $quantity=$quantity[$i]; function CheckIfQuantityIsEnough ($productCode,$quantity) { try { $QuantityIsEnough = false; $pdoAssigned = new PDOConfig; //Works perfectly well for one variable set $resultQuantityIsEnough = $pdoAssigned->query("call sp_getStockQuantityCount($productCode,$quantity)"); if( $resultQuantityIsEnough->fetchColumn() >0) //the course has been assigned { $QuantityIsEnough = true; } return $QuantityIsEnough; } catch (Exception $e) { throw $e; } } }//End For statement //Check also if Quantity is enough for that if (CheckIfQuantityIsEnough ($productCode,$quantity) == false) { $Feedback = "Quantity not enough for this product"; } ?> //sp_getStockQuantityCount CREATE PROCEDURE `sp_getStockQuantityCount`(`vStockTypeID` INT, `vQuantity` DECIMAL(9,0)) BEGIN declare vQuantityNow int; declare vQuantitySubtract int; set vQuantityNow=(select Quantity from stockquantitytbl where StockTypeID=vStockTypeID limit 1); set vQuantitySubtract=(vQuantityNow-vQuantity); select count(Quantity) from stockquantitytbl where StockTypeID=vStockTypeID and vQuantitySubtract>=0; END ---------------Edit----------------------- I have done away with the function and now just need to use the Stored Procedure as below: <?php //Array data //$productCode = array(2, 1, 7, 2); //$quantity = array(10, 20, 30, 40); //Single set $productCode=7; $quantity=101; $sql="call sp_getStockQuantityCount($productCode,$quantity)"; $result = $odb -> query($sql); if($result->rowcount() > 0) { foreach ($result as $row) { $QuantityIsEnough = $row['Quantity']; if($QuantityIsEnough == 0) { $Feedback = "Quantity not enough for this product"; } else { //Insert sale record } } } ?> One set works well, but the problem still remains on array data as explained above.
How to fetch and return record with total number of records in codeigniter
I am working with rest api using codeigniter,I want to fetch records + total records + per page records,but not worked for me Here is my function in controller <?php public function search_shop() { $users['rec'] = $this->Model_users->find_shop($_POST); if($users['rec']!="") { $responseJSON = array("Status" => true,"Result" => $users['rec']); header("content-type:application/json"); $response = json_encode($responseJSON); echo $response; } else { $responseJSON = array("Status" => false,"Message" => "There is no matching record"); header("content-type:application/json"); $response = json_encode($responseJSON); echo $response; } } And here is my "find_shop" function in model,How can i fetch all records with total number of records and per page records ? public function find_shop() { $add_data['page_number'] = ($this->input->post('page_number') && !empty($this->input->post('page_number'))) ? $this->input->post('page_number') : NULL; $add_data['search'] = ($this->input->post('search') && !empty($this->input->post('search'))) ? $this->input->post('search') : NULL; $records="10"; $mins="10"; if($add_data['page_number']=="" || $add_data['page_number']=="0" || $add_data['page_number']=="1") { $starting_row="0"; $last_row="10"; } else { $last_row="9"; $cd="1"; $lim="10"; $starting_row=$add_data['page_number']*$lim-$last_row-$cd; $last_row=$add_data['page_number']*$records-$cd; } $this->db->select('*'); $this->db->from('shop s'); $this->db->like('shop_name',$add_data['search']); $this->db->or_like('city',$add_data['search']); $this->db->limit($last_row,$starting_row); $query = $this->db->get(); if ( $query->num_rows() > 0 ) { $row = $query->result_array(); return $row; return $query->num_rows; } else { return false; } } ?>
Try This, Hope it helps in the Controller please test this after model related changes $users = array(); $users = $this->Model_users->find_shop($_POST); echo'<pre>';print_r($users);die; in the Model, There is a mistake in the return, You cannot do two return at the same time $query = $this->db->get(); if ( $query->num_rows() > 0 ) { $data = array(); $data['row'] = $query->result_array(); $data['total_records'] = $this->db->count_all_results('shop'); $data['per_page_records'] = $query->num_rows(); return $data; }else{ return array('row'=>array(),'total_records'=>'0','per_page_records'=>'0'); }
Change your if condition like this: $records="10"; // This is records per page showing if ($add_data['page_number']=="" || $add_data['page_number']=="0" || $add_data['page_number']=="1") { $starting_row="0"; } else { $starting_row = ($add_data['page_number'] - 1) * $records; } You need to set limit and offset of query. For example: limit 0, 10: this will show first 10 records. Here 0 is starting point and 10 is the length of records which you want to show. 10 will always be same as you are showing 10 records. Limit 10, 10: it will show records from 10 to 19. hope it clears your doubt.
Count Array where Column Value Equals Given
I have a controller where an array of checkbox values are passed on to the controller and then sent on to do a variety of tasks. My problem is focused on getting a count of the arrays' shipment's customer's billing method, but I'm not entirely sure how I would get those values since I'm posting an array and I want a count. Here's my controller: public function sendNow(Request $request) { $now = Carbon::now(); $sendNowShipment = array(); $method = array(); $sendNowShipment = request('send'); foreach($sendNowShipment as $SNS){ $shipment = Shipment::findOrFail($SNS); if($shipment->billtoAccount->billingMethods->label == "Mail"){ $timestamp = Carbon::now()->timestamp; $shipment_details = $shipment->shipment_details; $path = 'temp/freightbill_'.$shipment->pro_number.'-'.$timestamp.'.pdf'; $sessionPath[] = $path; $pdf = PDF::loadView('shipments.pdf', compact('shipment', 'shipment_details')) ->save($path); }elseif($shipment->billtoAccount->billingMethods->label == "Email"){ $billToAccount = $shipment->billtoAccount; $billToAccountUsers = $billToAccount->users; if ($billToAccount->primary_email){ $billToEmail[] = $billToAccount->primary_email; } if ($billToAccountUsers->count() > 0){ foreach ($billToAccountUsers as $billToAccountUser){ $billToEmail[] = $billToAccountUser->email; } } foreach ($billToEmail as $bte){ Mail::to($bte)->send(new newBillToShipment($shipment)); } } } if(count($shipment->billtoAccount->billingMethods->label == "Mail") > 0){// count where shipments->customers->billingMethods = Mail) > 0 $pdf = new PDFMerger(); // Add 2 PDFs to the final PDF foreach($sessionPath as $sp){ $pdf->addPDF($sp, 'all'); } // Merge the files and retrieve its PDF binary content $timestamp = Carbon::now()->timestamp; $binaryContent = $pdf->merge('download', $timestamp."-printBatch.pdf"); // Return binary content as response //return response($binaryContent) // ->header('Content-type' , 'application/pdf'); return back(); //dd($sendNowShipment,$sendMethod); } } If you look at this line (a little past the middle): if(count($shipment->billtoAccount->billingMethods->label == "Mail") > 0){ // count where shipments->customers->billingMethods = Mail) > 0 You'll see that I'm going through a multitude of relationships just to get the value of "Mail" that I am looking for. So I'm wondering if this should be a DB:: query through laravel, but I'm not sure how I would perform the query using the given checkbox array I have being POSTed to this controller.
Setting a variable to an operator then executing it
I'm new to PHP in general. I was messing with this code until I wanted to execute the function in one set instead of having to set and add, sub, div, mult function. How do I go about setting the variable operator with the two num sets? Example pseudo code: <?php $Num1 = 10; $Num2 = 5; $operation = /; $Sum = $Num1 $operation $Num2; return $Sum; Or something like: <?php // creating Class "Math" class math { //Executing the function function exec($info = array()) { return $info['num1'] $info['operation'] $info['num2']; } } // Set info $info = array( 'num1' => 10, 'num2' => 5, 'operation' => '/' ); //execute the OOP $math = new math; echo $math->exec($info);
What you are asking for is referred to as the Strategy Pattern. One way to do this is to define your functions $multiply = function($operand0, $operand1) { return $operand0*$operand1; }; $add = function($operand0, $operand1) { return $operand0+$operand1; }; Then using your sample code: class math { //Executing the function function exec($info = array()) { return $info['operation']($info['num1'], $info['num2']); } } // Set info $info = array( 'num1' => 10, 'num2' => 5, 'operation' => $add ); //execute the OOP $math = new math; echo $math->exec($info); //will print 15