I'm playing with OOP in PHP.
I have this code in my index.php
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Numbers Class</title>
</head>
<body>
<?php
require_once("numbers.php");
$numbers->start("1","2","3");
echo $numbers->list_numbers();
?>
</body>
</html>
And this in my numbers.php
<?php
// Class creation
class numbers
{
private $n1, $n2, $n3;
// Method creation
public function start ($n1,$n2,$n3)
{
$this->number1=$n1;
$this->number2=$n2;
$this->number3=$n3;
}
public function list_numbers()
{
return $this->number1;
return $this->number2;
return $this->number3;
}
}
// Object instance
$numbers=new numbers();
?>
Now, if what I have read so far about oop in PHP, my output should be
1
2
3
But I'm only getting
1
Why???
What I'm doing wrong???
I'm creating a new object called numbers, it has 3 attributes, I created 2 methods, one for storing the numbers and another to call them back.
I load the class and send the numbers, but somehow I'm failing when calling them back. I lost the second and third number, and I just don't understand why...
With return you're getting out of the function, you can use it only once per function so.
I guess what you want is the echo function
public function list_numbers()
{
echo $this->number1;
echo $this->number2;
echo $this->number3;
}
In your list_numbers() method, you are returning the first value. From http://php.net/manual/en/function.return.php
If called from within a function, the return statement immediately ends execution of the current function, and returns its argument as the value of the function call. return will also end the execution of an eval() statement or script file.
If you replaced return with echo in your list_numbers() method, you would get the output you are expecting.
Also, you didn't "lose" the numbers. You can verify this by doing a var_dump($this).
Antoine's and Ben's explanations are good, but the suggested repair might also be
public function list_numbers()
{
return array($this->number1, $this->number2, $this->number3);
}
In this case, you get array from the function by
$nums = $numbers->list_numbers();
You can now print this array or do anything else you might want with it, the same way you would do it with any other array.
Change to this...
public function list_numbers()
{
return array($this->number1, $this->number2,return $this->number3);
}
Then in your php file....
<?php
require_once("numbers.php");
$numbers->start("1","2","3");
$nums = $numbers->list_numbers();
//use it in a loop or just print_r it or whatever....
foreach($nums as $val){
echo "Number is : ".$val;
}
Related
Is it possible to call only the specific function from another file without including whole file???
There may be another functions in the file and don't need to render other function.
The short answer is: no, you can't.
The long answers is: yes, if you use OOP.
Split your functions into different files. Say you are making a game with a hero:
Walk.php
function walk($distance,speed){
//walk code
}
Die.php
function die(){
//game over
}
Hero.php
include 'Walk.php';
include 'Die.php';
class Hero(){
//hero that can walk & can die
}
You may have other functions like makeWorld() that hero.php doesn't need, so you don't need to include it. This question has been asked a few times before: here & here.
One of the possible methods outlined before is through autoloading, which basically saves you from having to write a long list of includes at the top of each file.
In PHP it's not available to get only a little part of a file.
Maybe this is a ability to use only little parts of a file:
I have a class that calls "utilities". This I am using in my projects.
In my index.php
include("class.utilities.php")
$utilities = new utilities();
The file class.utilities.php
class utilities {
function __construct() {
}
public function thisIsTheFunction($a,$b)
{
$c = $a + $b;
return $c;
}
}
And then i can use the function
echo $utilities->thisIsTheFunction(3,4);
include a page lets say the function is GetPage and the variable is ID
<?php
require('page.php');
$id = ($_GET['id']);
if($id != '') {
getpage($id);
}
?>
now when you make the function
<?php
function getpage($id){
if ($id = ''){
//// Do something
}
else {
}
}
?>
I am trying to setup an array that pulls the filename and function name to run, but it not fully working.
The code is
$actionArray = array(
'register' => array('Register.php', 'Register'),
);
if (!isset($_REQUEST['action']) || !isset($actionArray[$_REQUEST['action']])) {
echo '<br><br>index<br><br>';
echo 'test';
exit;
}
require_once($actionArray[$_REQUEST['action']][0]);
return $actionArray[$_REQUEST['action']][1];
Register.php has
function Register()
{
echo 'register';
}
echo '<br>sdfdfsd<br>';
But it does not echo register and just sdfdfsd.
If I change the first lot of code from
return $actionArray[$_REQUEST['action']][1];
to
return Register();
It works, any ideas?
Thanks
Change the last line to:
return call_user_func($actionArray[$_REQUEST['action']][1]);
This uses the call_user_func function for more readable code and better portability. The following also should work (Only tested on PHP 5.4+)
return $actionArray[$_REQUEST['action']][1]();
It's almost the same as your code, but I'm actually invoking the function instead of returning the value of the array. Without the function invocation syntax () you're just asking PHP get to get the value of the variable (in this case, an array) and return it.
You'll find something usefull here:
How to call PHP function from string stored in a Variable
Call a function name stored in a string is what you want...
I'm using an html parser to scrape html and then format it so that it can be inserted to the DB.
require_once('simple_html_dom.php');
$url = "http://www.site.com/url/params/"
$html = file_get_html($url);
// The team links are stored in the div.thumbHolder
foreach($html->find('.logoWall li') as $e)
{
ob_start();
sportPics($e, $league);
}
The sportsPics() function is this:
function sportsPic()
{
require('simple_html_dom.php');
foreach($e->find('a') as $a)
{
// Execute code
}
}
I get an error reading:
Fatal error: Cannot redeclare file_get_html()
I thought changing require() to require_once() and vice versa would work. But, it didn't. I also thought a buffer might work but I don't know too much about how they work.
Don't do this again -
require('simple_html_dom.php');
in sportsPic() function.
Update - Your function definition function sportsPic() takes no argument. But look at this line -
sportPics($e, $league);
Redefine your function to take arguments.
You are passing arguments but the function has no way to access them as it takes no arguments. And hence, your $e is a non-object.
Put this out sided sportsPic() function
require('simple_html_dom.php');
you are calling this again & again in a loop.
foreach($html->find('.logoWall li') as $e){
foreach($e->find('a') as $a){
// Execute code
}
}
Is it possible to have return statements inside an included file that is inside a function in PHP?
I am looking to do this as I have lots of functions in separate files and they all have a large chunk of shared code at the top.
As in
function sync() {
include_once file.php;
echo "Test";
}
file.php:
...
return "Something";
At the moment the return something appears to break out of the include_once and not the sync function, is it possible for the included file's return to break out?
Sorry for the slightly odly worked question, hope I made it make sense.
Thanks,
You can return data from included file into calling file via return statement.
include.php
return array("code" => "007", "name => "James Bond");
file.php
$result = include_once "include.php";
var_dump("result);
But you cannot call return $something; and have it as return statement within calling script. return works only within current scope.
EDIT:
I am looking to do this as I have lots
of functions in separate files and
they all have a large chunk of shared
code at the top.
In this case why don't you put this "shared code" into separate functions instead -- that will do the job nicely as one of the purposes of having functions is to reuse your code in different places without writing it again.
return will not work, but you can use the output buffer if you are trying to echo some stuff in your include file and return it somewhere else;
function sync() {
ob_start();
include "file.php";
$output = ob_get_clean();
// now what ever you echoed in the file.php is inside the output variable
return $output;
}
I don't think it works like that. The include does not simply put the code in place, it also evaluates it. So the return means that your 'include' function call will return the value.
see also the part in the manual about this:
Handling Returns: It is possible to
execute a return() statement inside an
included file in order to terminate
processing in that file and return to
the script which called it.
The return statement returns the included file, and does not insert a "return" statement.
The manual has an example (example #5) that shows what 'return' does:
Simplified example:
return.php
<?php
$var = 'PHP';
return $var;
?>
testreturns.php
<?php
$foo = include 'return.php';
echo $foo; // prints 'PHP'
?>
I think you're expecting return to behave more like an exception than a return statement. Take the following code for example:
return.php:
return true;
?>
exception.php:
<?php
throw new exception();
?>
When you execute the following code:
<?php
function testReturn() {
echo 'Executing testReturn()...';
include_once('return.php');
echo 'testReturn() executed normally.';
}
function testException() {
echo 'Executing testException()...';
include_once('exception.php');
echo 'testException() executed normally.';
}
testReturn();
echo "\n\n";
try {
testException();
}
catch (exception $e) {}
?>
...you get the following output as a result:
Executing testReturn()...testReturn() executed normally.
Executing testException()...
If you do use the exception method, make sure to put your function call in a try...catch block - having exceptions flying all over the place is bad for business.
Rock'n'roll like this :
index.php
function foo() {
return (include 'bar.php');
}
print_r(foo());
bar.php
echo "I will call the police";
return array('WAWAWA', 'BABABA');
output
I will call the police
Array
(
[0] => WAWAWA
[1] => BABABA
)
just show me how
like this :
return (include 'bar.php');
Have a good day !
I have several functions in a class that return saveHTML(). After I echo more than one function in the class saveHTML(), it repeats some of the HTML. I initially solved this by doing saveHTML($node) but that doesn't seem to be an option now.
I didn't know saveHTML($domnode) was only available in PHP 5.3.6 and I have no control over the server I uploaded the files to so now I have to make it compatible with PHP 5.2.
For simplicity's sake it and only to show my problem it looks similar to this:
<?php
class HTML
{
private $dom;
function __construct($dom)
{
$this->dom = $dom;
}
public function create_paragraph()
{
$p = $this->dom->createElement('p','Text 1.');
$this->dom->appendChild($p);
return $this->dom->saveHTML();
}
public function create_paragraph2()
{
$p = $this->dom->createElement('p','Text 2.');
$this->dom->appendChild($p);
return $this->dom->saveHTML();
}
}
$dom = new DOMDocument;
$html = new HTML($dom);
?>
<html>
<body>
<?php
echo $html->create_paragraph();
echo $html->create_paragraph2();
?>
</body>
</html>
Outputs:
<html>
<body>
<p>Text 1.</p>
<p>Text 1.</p><p>Text 2.</p>
</body>
I have an idea why it's happening but I have no idea how to not make it repeat without saveHTML($domnode). How can I make it work properly with PHP 5.2?
Here's an example of what I want to be able to do:
http://codepad.viper-7.com/o61DdJ
What I do, is just save the node as XML. There are a few differences in the syntax, but it's good enough for most uses:
return $dom->saveXml($node);
You have return $this->dom->saveHTML(); twice in your class ( as far as I know you don't have to return it inside the class anywhere unless it is a private function.
If you take return $this->dom->saveHTML(); out of createparagraph() it will echo without returning. It's a DOM thing as far as I know but am new to this like you.