how to define new various in PHP function - php

I want to define new variable in a function .
function show()
{//for e.g
$name = "john";
$family = "cina";
$old = "45";
}
show();
echo "your name is $name ";//in another line
echo "your family is $family ";//in another line
echo "your old is $old ";//in another line
Thanks

You could also consider using list(); you'll have to make a slight change to your function but it'll work.
function show(){
$name = "john";
$family = "cina";
$old = "45";
return array($name,$family,$old);
}
list($name,$family,$old) = show();
echo $name;
echo $family;
echo $old;
Be aware that the order matters, the first value in the return array will be assigned to the first variable in the list(); and the second array value to the second variable in the list, and so on.

Write echo inside function as below
function show()
{
$name = "john";
$family = "cina";
$old = "45";
echo $name." ".$family." ".$old;
}
show();

function show()
{
$name = "john";
$family = "cina";
$old = "45";
return $name." ".$family." ".$old;
}
echo show();
This

Return it from your function like this
function show()
{//for e.g
$name = "john";
$family = "cina";
$old = "45";
return $name . " " . $family . " " . $old;
}
$result = show();
echo $result;

you can use also in the following way
function show()
{
$name = "john";
$family = "cina";
$old = "45";
return $name." ".$family." ".$old;
}
echo $res = show(); // john cina 45

This is how I should do it =)
<?php
function show()
{
$name = "john";
$family = "cina";
$old = "45";
echo $name." ".$family." ".$old;
}
show();
?>

As a general rule, don't do this. It's not very good and looks terrible, but this is what you need.
<?php
$name = null;
$family = null;
$old = null;
function show()
{
global $name, $family, $old;
$name = "john";
$family = "cina";
$old = "45";
}
show();
echo "your name is $name ".PHP_EOL;
echo "your family is $family ".PHP_EOL;
echo "your old is $old ".PHP_EOL;
I will recommend an alternative way of writing this (one of many). You can check other answers for different ways.
class Singleton {
public static $name;
public static $family;
public static $old;
}
function show()
{
Singleton::$name = "john";
Singleton::$family = "cina";
Singleton::$old = "45";
}
show();
echo "your name is ".Singleton::$name;//in another line
echo "your family is ".Singleton::$family;//in another line
echo "your old is ".Singleton::$old;//in another line

Related

Need help on simple PHP loop to run on class objects

I am looking for a way to make this foreach loop run on the UserData objects.
<?php
echo '<pre>';
class UserData{
public $FName;
public $LName;
public $IP;
}
$user001 = new UserData();
$user002 = new UserData();
$user003 = new UserData();
$user001->FName = 'Erez';
$user001->LName = 'T';
$user001->IP = '192.168.0.1';
$user002->FName = 'Netali';
$user002->LName = 'Goz';
$user002->IP = '192.168.0.2';
$user003->FName = 'Charley';
$user003->LName = 'Abu Ben David';
$user003->IP = '192.168.0.3';
So up to here the class has the attributes picked up by the new objects above.
Now from this part below I'm using the get_object_vars to retrieve the UserData but I have no idea how to run it dynamically.
Can you help me with this in the shortest code possible with the most basic code?
(a for loop would be great!)
$vars = get_object_vars('UserData');
print_r($vars);
echo '<hr>';
foreach ($vars as $OP =>$OPVal){
echo $OP .' is '.$OPVal.'<br>';
}
You can disregard the print_r and echo's.
Thanks!
you can loop with this methode
for($x=1;$x<4;$x++){
$vars = get_object_vars(${'user00'.$x});
print_r($vars);
echo '<hr>';
foreach ($vars as $OP =>$OPVal){
echo $OP .' is '.$OPVal.'<br>';
}
echo '<hr>';
}
but, you better learn OOP concept first.
Instead of making individual instances of the object, create an array of objects, and add as many as you need.
You can also add a constructor for the class, to instantiate easier.
Example:
class UserData{
public $FName;
public $LName;
public $IP;
public function __construct($fname,$lname,$ip){
$this->FName = $fname;
$this->LName = $lname;
$this->IP = $ip;
}
}
//store your data in some arrays
$firstNames = array('Erez','Netali','Charley');
$lastNames = array('T','Goz','Abu Ben David');
$ips = array('192.168.0.1','192.168.0.2','192.168.0.3');
$users = array();
for ($i=0;$i<3;$i++){
// instantiate each new object using data from the above arrays
$users[] = new UserData($firstNames[$i],$lastNames[$i],$ips[$i]);
// or use your method
/*
$users[] = new UserData('Netali','Goz','192.168.0.2')
*/
}
// now iterate over your array of UserData objects and print their properties
foreach ($users as $user){
print $user->FName . ", " . $user->LName . ", " . $user->IP . PHP_EOL;
}
// outputs
Erez, T, 192.168.0.1
Netali, Goz, 192.168.0.2
Charley, Abu Ben David, 192.168.0.3

Php doing a for loop with OOP,can't figure out how

i have this code below:
<?php
class Product {
public $name;
public $desc;
public $price;
public $category;
public $qty;
public $model;
public $manufacturer;
function display() {
$output = '';
$output .= $this->name ."</br>";
$output .= $this->desc . "</br>";
$output .= $this->price "</br>";
$output .= $this->category "</br>";
$output .= $this->qty "</br>";
$output .= $this->model "</br>";
$output .= $this->manufacturer "</br>";
return $output;
}
}
$product = new Product();
$product->name = "Samsung galaxy s6";
$product->desc = "It's kind of good but meh";
$product->price = "1000 GBP";
$product->category = "Phones";
$product->qty = "Quantity:999";
$product->model = "Samsung s6";
$product->manufacturer = "Phone guys";
echo $product->display();
?>
So this function works without a problem by itself when i set the values in:
$product->name = "Samsung galaxy s6";
$product->desc = "It's kind of good but meh";
$product->price = "1000 GBP";
$product->category = "Phones";
$product->qty = "Quantity:999";
$product->model = "Samsung s6";
$product->manufacturer = "Phone guys";
So when i set all the values everything works,but my question is: Is it possible for me to make each one of those an array lets say i want to display 2 products in the browser
When I set the $product->name to $product->name = array("Samsubg","Iphone","Apple");
This by itself displays only **Apple* and i kind of get lost here on what to do
Thanks.
You normally would use a setter method to set variables and it would look like this if you wanted to set it as an array.
private name = array();
public function setName($name) {
$this->name[] = $name;
}
You would want to do this with all your variables. If you wanted to pass in an array you could loop through it and pass one at a time or pass the whole array you would want to set your setter function like this:
private name = array();
public function setName($name) {
$this->name = $name;
}
You could then set it by calling the method and passing in the array.
$product->setName($myArrayOfNames);
With OOP, it doesn't make sense to have a single object with fields that are arrays. That is just procedural programming in an object.
Instead, the fields of each object should describe the state of only the object itself. If you need an array to describe multiple products, then you simply make an array of the Product object.
$products = array();
$product_one = new Product();
$product_one->name = "Samsung galaxy s6";
$product_one->desc = "It's kind of good but meh";
$product_one->price = "1000 GBP";
$product_one->category = "Phones";
$product_one->qty = "Quantity:999";
$product_one->model = "Samsung s6";
$product_one->manufacturer = "Phone guys";
$product_two = new Product();
$product_two->name = "iPhone6";
$product_two->desc = "who knows";
$product_two->price = "10000 GBP";
$product_two->category = "Phones";
$product_two->qty = "Quantity: 1";
$product_two->model = "iPhone";
$product_two->manufacturer = "Apple";
$products[] = $product_one;
$products[] = $product_two;
foreach($products as $product) {
echo $product->display();
}
Define your array property in the class, here is a full working example.
class Body
{
private $name = array();
public function setName($name)
{
$this->name = $name;
}
public function getName()
{
return $this->name;
}
}
$user = new Body();
$user->setName(array("Samsubg","Iphone","Apple"));
echo var_dump($user->getName()); This will dump an array, all you have to do is do a for loop over it or get the array values by index: $user->getName[0].

I'm passing too many parameters

I'm passing a lot of parameters in a function
I want to know if its wrong what i am doing and if it is possible to put all those variables into an array and just call the array:
Here my function parameters:
function addjo($logo, $job_category, $job_name, $status, $localization, $job_type, $contract_type, $description)
My code to recognize all the variables.
if (isset($_POST['add_jo'])){
$job_category =$_POST['job_category'];
$description = $_POST['description'];
$job_name = $_POST['job_name'];
$logo = $_POST['logo'];
$status = $_POST['status'];
$localization = $_POST['localization'];
$job_type = $_POST['job_type'];
$contract_type = $_POST['contract_type'];
addjo($logo, $job_category, $job_name, $status, $localization, $job_type, $contract_type, $description);
}else{
$logo = NULL;
$job_category = NULL;
$job_name = NULL;
$status = NULL;
$localization = NULL;
$description = NULL;
$job_type = NULL;
$contract_type = NULL;
$check1 = NULL;
$check2 = NULL;
}
Is it possible to do something like this?
if(isset($_POST['mybutton'])){
array[](
$var1 = $_POST['var1'];
$var2 = $_POST['var2'];
);
function(callarrayhere);
else{
$var1 = null;
$var2 = null;
}
Thanks.
Since $_POST is already an array, just use it:
addjob($_POST);
And in addjob:
function addjob($input) {
// verify that array items are present and correct.
}
Exporting an array's values to individual variables is not only a waste of time and memory, but it also makes your code harder to read (where do these variables come from? It's not obvious they came from the same source array)
Of course it's possible:
if (isset($_POST['add_jo'])){
$a = array();
$a['job_category'] =$_POST['job_category'];
$a['description'] = $_POST['description'];
// and so on
$a['contract_type'] = $_POST['contract_type'];
addjo($a);
}
else
{
$a['job_category'] = null;
// and so on
}
And in function addjo you can display all values that way:
function addjo($a) {
foreach ($a as $k => $v) {
echo $k.' '.$v."<br />"
}
// or
echo $a['job_category'];
}
Yes it is possible to have an array as an argument to a function. Your syntax isn't quite right. This would do it:
function addjo($params){
echo $params['logo'];
echo $params['job_category'];
echo $params['job_name'];
}
Usage example:
$arr = array(
'logo' => $logo,
'job_category' => $job_category,
'job_name' => $job_name
);
addjo($arr);
You could also have default parameters for each of the array elements, or make them optional. See this answer for how to do that.

getting the arguments (list) of a specific (user defined ) PHP function

is there a way to achieve this in PHP?
echo list_args('a_user_defined_function_name_here_such_as_say_hello');
and this outputs something like
$first_name
$last_name
for a function defined as;
function say_hello($first_name, $last_name){
echo "Hello $first_name $last_name";
}
So basically, what I'm looking for is a function explainer or something of that sort... & if that thing can get into a php doc based comment extractor. that would be even better..
You could use the ReflectionFunction class to do this:
function list_args($name) {
$list = "";
$ref = new ReflectionFunction($name);
foreach ($ref->getParameters() as $param) {
$list .= '$' . $param->getName() . "\n";
}
return $list;
}
You can try ReflectionFunction.
function list_args($function) {
$func = new ReflectionFunction($function);
$res = array();
foreach ($func->getParameters() as $argument) {
$res[] = '$' . $argument->name;
}
return $res;
}
print_r(list_args('say_hello')); // outputs Array ( [0] => $first_name [1] => $last_name )

Declares values on objects and output the values

I need some guide or reference on how should I do this.
What I should do is, have a class structure named Cat and have a static method that outputs new object.
class Cat{
public $name;
public $age;
public $string;
static public function ToData($Cat) {
$input = "";
foreach ($Cat as $key => $value) {
$input .= "object: " . $key . "</br>";
}
return $input;
}
}
$name = "meow";
$age = "12";
$string = "'test', 'sample', 'help'";
$Cat = array($name, $age);
$output = Cat::ToData($Cat);
echo $output;
This is the best thing that I can come up with
here is the problem, they said I just used an array and not an object.
I used array because I have to put the values on the $Cat so it can be passed on the parameter.
Looks like it's an assignment on object-oriented programming concept in PHP. I believe this is what you're trying to accomplish, with comments explaining the steps.
class Cat{
public $name;
public $age;
// Output the attributes of Cat in a string
public function ToData() {
$input = "";
$input .= "object: name :".": ".$this->name." </br>";
$input .= "object: age :".": ".$this->age." </br>";
return $input;
}
}
$name = "meow";
$age = "12";
// Instantiate Cat
$Cat = new Cat();
$Cat->name = $name;
$Cat->age = $age;
// Output Cat's attributes
$output = $Cat->ToData();
echo $output;
if you want to set those values to the object here is what you do
...
foreach ($Cat as $key => $value) {
$this->$key = $value;
}
...
$name = "meow";
$age = "12";
$Cat = array("name"=>$name,"age"=> $age);
$cat = new Cat();
$cat->toData($Cat);
echo $cat->name;
// meow
Update:
Now i get a better idea what you are trying to do, this is how your class will look like:
class Cat{
public $name;
public $age;
public $string;
static public function ToData($Cat) {
$obj = new self();
$obj->name = $Cat["name"];
$obj->age = $Cate["age"];
$obj->string = $Cate["string"];
return $obj;
}
// echo
public function __toString(){
return "$this->name - $this->age - $this->string";
}
}
now you can set your values
$name = "meow";
$age = "12";
$string = "'test', 'sample', 'help'";
$Cat = array($name, $age,$string);
$output = Cat::ToData($Cat);
echo $output;
Note that $output is an object

Categories