Need to create function that will call other built-in and custom functions, problem is that each called function has different number of parameters.
I supply to a callerFunction required function name and required parameters in array, but how do i implement the actual function call?
P.S. I am aware of function scope, this is not a question now.
function myFunction(inputStr, paramOne, paramTwo) {
echo inputStr . " P1: " . paramOne . " P2: " . paramTwo;
}
function callerFunction(functName, functArgsArr) {
$myVar = "";
n = 1;
while n <= functArgsArr.length {
myVar = myVar . " " . functArgsArr[n];
n++;
}
%functName%("Hello World!", %myVar%);
}
callerFunction("myFunction", ["one", "two"]);
You could use the call_user_func_array PHP function:
<?php
function myFunction($inputStr, $paramOne, $paramTwo)
{
echo $inputStr . " P1: " . $paramOne . " P2: " . $paramTwo;
}
function callerFunction($functionName, array $functArgsArr)
{
// Prepends 'Hello World' to args array
array_unshift($functArgsArr, "Hello World");
// Calls $functionName passing the values of $functArgsArray as arguments
call_user_func_array($functionName, $functArgsArr);
}
callerFunction("myFunction", ["one", "two"]);
Working PHP Fiddle
Related
Hi I am new to PHP and I need to create an array and add both books to the array and than loop through the array this is where I am having trouble
if the price of a book is less than $20.00 output the book’s name and price
if the book’s title comes after the letter R in the alphabet output the book’s title.
My code so far is:
<?php
class Book {
// Properties
public $price;
public $title;
// Methods
function set_price($price) {
$this->price = $price;
}
function get_price() {
return $this->price;
}
function set_title($title) {
$this->title = $title;
}
function get_title() {
return $this->title;
}
}
$first_book = new Book();
$first_book->set_price('$13.95');
$first_book->set_title('Moby Dick');
echo "Price: " . $first_book->get_price();
echo "<br>";
echo "Title: " . $first_book->get_title();
echo "<br>";
$second_book = new Book();
$second_book->set_price('$23.99');
$second_book->set_title('Wuthering Heights');
echo "Price: " . $second_book->get_price();
echo "<br>";
echo "Title: " . $second_book->get_title();
echo "<br>";
$book = array("Moby Dick", "Wuthering Heights");
echo "Book Titles: " . $book[0] . ", " . " and " . $book[1] . ".";
?>
Kind Regurds
Kelly
Seems like you got most of it already, for the rest I would add a function to your Book class to get the first character of the title, and then use the ord (PHP documentation here) to convert it to an integer so you can check if it comes after the letter R.
<?php
// Add this to your Book class to get the first character of the title so we can check
// if the book comes after the letter 'R'
public function get_first_char() {
$titleArray = str_split($this->title);
return reset($titleArray);
}
// Instantiate your books and set properties ...
// Loop over each book
foreach ($book as $bookItem) {
$price = $bookItem->price;
// Right now $price is a string ('$xx.xx'), we need it to be numeric
$price = (float) substr($price, 1);
if ($price < 20) {
echo $bookItem->title;
echo $bookItem->price;
}
// Use the ord function to convert the ascii character into an int
if (ord(strtoupper($bookItem->get_first_char())) > ord('R')) {
echo $bookItem->title;
}
}
?>
I am not the best at php but currently I am trying to learn. I can print fine outside of the function but the specific instructions I have been given require me to print the results within the function. I have tried
echo "$area";
echo "calculatearea ()";
ive searched but still cant figure out how to get a print within the function only outside of it.
<?php
if (isset($_POST['CalcBT'])) {
global $area;
function calculateCircumference () {
$num1 = ($_POST['Length']);
$num2 = ($_POST['Width']);
$circ = $num1 + $num2;
return $circ;
}
function calculateArea () {
$num1 = ($_POST['Length']);
$num2 = ($_POST['Width']);
$area = 2*($num1 + $num2);
return $area;
}
echo "Your rectangle circumference is: " . calculateCircumference() . '<br />' . "Your rectangle area is: " . calculateArea();
}
?>
<!---------------- Form---------------->
<div class="form">
<h3></h3>
<form action="PHP-sida4.php" method="POST">
<p>Length: <input type="text" name="Length"value=""></p>
<p>Width: <input type="text" name="Width"value=""></p>
<input type="submit" name="CalcBT" value="Calculate">
</form>
I need the return value of $area along with what I echo'd in the bottom to actually print within the first function ( calculateCircumference )
You can echo anything you want within the function but it won't show up until you call the function.
<?php
if (isset($_POST['CalcBT'])) {
global $area;
function calculateCircumference () {
$num1 = ($_POST['Length']);
$num2 = ($_POST['Width']);
$circ = $num1 + $num2;
// return $circ;
echo "Your rectangle circumference is: " . $circ . '<br />' . "Your rectangle area is: " . calculateArea();
return;
}
function calculateArea () {
$num1 = ($_POST['Length']);
$num2 = ($_POST['Width']);
$area = 2*($num1 + $num2);
return $area;
}
calculateCircumference();
}
?>
I hope this helps!
Okay if am getting your question right, to need to return the area and some other text along with the area.
Let's begin with some house cleaning, therefore the $area global variable could be renamed to something else like $results Which will be an array or object. Taking it simple.
Lets go with an associative array where e.g:
$results = [
'area' => null,
'text' = null
];
From that your will be updating $results['area'] from the calculate function and also update the $results['text'] before calling echo, so probably extract the echoed text to another variable.
And now you can access $results anywhere within the file with both the area and the text:
To just be more expressive under CalculateArea() function do something like:
$results['area'] = $area;
Same thing with the echoed text.
You can use echo instead of return in your functions. To call them, your can just use function(); without any additional keyword :
function calculateCircumference () {
$num1 = ($_POST['Length']);
$num2 = ($_POST['Width']);
$circ = $num1 + $num2;
echo $circ;
}
function calculateArea () {
$num1 = ($_POST['Length']);
$num2 = ($_POST['Width']);
$area = 2*($num1 + $num2);
echo $area;
}
echo "Your rectangle circumference is: " ;
calculateCircumference() ;
echo '<br />' ;
echo "Your rectangle area is: " ;
calculateArea();
You can echo anything anywhere, be it inside a function or outside of it. If an echo is not performing, then there was either an error, or the line where the echo can be found was not executed.
In our case you have removed the echo after your functions, which, coincidentally happened to be the only place where they were called.
I have problem with variable in function - I define variable outside the function, increments the var in function and displays var outside function.
My code already looks like this:
$count = 10;
$decrease_count = function() use (&$count) {
$count--;
};
$decrease_count();
echo $count;
$added_records = 0;
Excel::filter("chunk")->selectSheetsByIndex(0)->load("storage\XYZ.xls")->chunk(250, function($reader) use (&$added_records, $part_catalogs, $parts, $cars, $car_models, $brands, &$importHelper) {
$added_records++;
echo "ADDED RECORDS LOCAL: " . $added_records . "<br>";
});
echo "<h2>Added " . $added_records . " records</h2>";
echo ADDED RECORDS LOCAL returns 1, so the $added_records++ works
Results: echo $count returns 9, but echo "Added " . $added_records (...) returns 0...
How to increment this $added_records variable??
I am creating simple calculator. I am just learning php and this is a small project.I have created a calculator with two inputs but I am now testing it with just one. It works but only if you type number+number. It doesn't work if it is number+number+number.
I would like that it would work if you inputted 2+2+2... or 2*2*2... or 6-2-2... and 2/2/2...
Code:
// Create Variables
$y = $_POST["input1"];
// Echo input value on screen
echo "<p>Operation: " . $y . "</p>";
// Validation
if(empty($y)){
?>
<script>
$(document).ready(function(){
$('#error').append('Error: Your Input is empty');
});
</script>
<?php
}elseif(preg_match("/[a-zA-Z]/", $y)){
?>
<script>
$(document).ready(function(){
$('#error').append('Error: You can only input numbers');
});
</script>
<?php
}else{
// Calculation Brain FOR + Operator
if (strpos($y,'+') !== false) {
$omega = substr($y, 0, strpos($y, '+'));
$alpha = substr($y, strpos($y, '+') + 1);
echo "<p>Omega: " . $omega . "</p>";
echo "<p>Alpha: " . $alpha . "</p>";
$gamma = $omega + $alpha;
// The Sum FOR + operator
echo "Calculation: " . $gamma;
}
}
That's usually a bad practice, but here you can use eval. But you have first to check that your string doesn't contains disallowed characters.
$allowedCharacters = "0123456789./*-+()% ";
if(preg_match('/^[^'.preg_quote($allowedCharacters).']+$/'), $y) {
eval('$result = '.$y.';');
echo "Calculation: " . $result;
}
The only problem is that you'll not be able to handle errors.
you could use this for the same operation
$test='2+2*3';
eval('$calc = '.$test.';');
echo "Calculation: " . $calc;
the out should be : 8
I am wanting to use the get_class($var) to show the class of an object. What would be the best way to do this? My code at the moment is:
abstract class userCharacter {
var $cName;
var $cLevel = 0;
var $cHP = 50;
var $cMP = 20;
function __construct($n) {
$this->cName = $n;
}
function showDetails() {
echo $this->cName . "<br />";
echo "Level: " . $this->cLevel . "<br />";
echo "HP: " . $this->cHP . "<br />";
echo "MP: " . $this->cMP . "<br />";
}
} // userCharacter
class warrior extends userCharacter {
} // warrior
And I create the object with:
$charOne = new warrior($name);
What I'm wanting to do is in the showDetails() function of the userCharacter class have a line similar to:
echo "Class: " . get_class($charOne) . "<br />";
But, I'm pretty sure that this won't work because the $charOne variable isn't in the right scope.
I'm thinking that I would need to declare $charOne with something like:
global $charOne = new warrior($name);
Would this work? If not, what is the best way to do this, if possible at all?
You want
echo get_class($this) ;
At runtime, the actual class will be figured out. That's what is cool about polymorphism.
However, even better, you want to do something like this:
echo $this->getClassDisplayName();
Then write that function for each subclass.
Or, the base class can have this type of function:
function getClassDisplayName()
{
return ($this->classDisplayName == "" ? getClass($this) : $this->classDisplayName );
}
Then in the constructor of your subclasses:
public __construct()
{
$this->classDisplayName = "The Mighty Warriors of Azgoth";
}