PHP OOP by simply adding two numbers - php

<?php
class SimpleClass{
var $number1;
var $number2;
public function input_two_no($num1,$num2){
$this->number1=$num1;
$this->number2=$num2;
}
public function the_sum(){
$total = $number1+$number2;
return $total;
}
public function output_the_sum(){
echo $total;
}
$numbers = new SimpleClass;
$numbers->input_two_no(10,5);
$numbers->the_sum();
$numbers->output_the_sum();
}
?>
Please point out where i am going wrong in this.I am not getting the output yet.

There are several things you're doing wrong, such as:
Take this code block $numbers = new SimpleClass; ... $numbers->output_the_sum(); outside of the class.
See this statement inside the_sum() method,
$total = $number1+$number2;
You didn't declare any local variables named $number1 and $number2 inside the_sum() method. Instead, you should make use of the instance variables here.
See this statement in output_the_sum() method,
echo $total;
You didn't declare any local variable named $total inside output_the_sum() method. Instead, create an instance variable named $total and store the sum value in this instance variable. Later, you can display the total sum value using echo $this->total;.
So your code should be like this:
class SimpleClass{
var $number1;
var $number2;
var $total;
public function input_two_no($num1,$num2){
$this->number1=$num1;
$this->number2=$num2;
}
public function the_sum(){
$this->total = $this->number1+$this->number2;
}
public function output_the_sum(){
echo $this->total;
}
}
$numbers = new SimpleClass;
$numbers->input_two_no(10,5);
$numbers->the_sum();
$numbers->output_the_sum();

First off, you don't need the 2 Methods. input_two_no($num1,$num2) and output_the_sum(). You may, however, create a basic constructor method. Secondly, to access member-variables (Properties), you need to use php object-access notation (->). your class should have been as shown below. the sum method itself returns the sum of the 2 numbers passed as arguments.
class SimpleClass{
var $number1;
var $number2;
public function __construct($num1=null, $num2=null){
$this->number1 = $num1;
$this->number2 = $num2;
}
public function the_sum($number1=null, $number2=null){
if(!is_null($number1) && !is_null($number2)){
return null;
}
if( (!is_int($number1) || !is_float($number1) || !is_double($number1)) &&
(!is_int($number2) || !is_float($number2) || !is_double($number2))
){
return 'Numeric inputs only...';
}
$this->number1 = $number1;
$this->number2 = $number2;
return $this->number1 + $this->number2;
}
}
$numbers = new SimpleClass;
$output = $numbers->the_sum(10,5);
echo $output; //<== YIELDS 15

Related

How can i change the value of $number here

I want to create a class. Each time it will be called it will increase the value of $number by 1. When it will reach 7, it should return a message "Maximum limit reached". Where to define the $number and how to store the new value in it.
class addClass
{
public $number = 0;
public static function addOne($number)
{
$number = $number++;
if ($number == 7) {
return 'This is 7';
}
}
}`
I think this is what you are looking for based on your description:
class MyNumber {
private static $number = 0;
public static function addOne() {
self::$number++;
if (self::$number === 7) {
return 'Maximum limit reached';
}
return self::$number;
}
}
$result = MyNumber::addOne();
$result = MyNumber::addOne();
$result = MyNumber::addOne();
$result = MyNumber::addOne();
$result = MyNumber::addOne();
$result = MyNumber::addOne();
$result = MyNumber::addOne();
First result is 1
Second result is 2
Third result is 3
Fourth result is 4
Fifth result is 5
Sixth result is 6
Seventh result is Maximum limit reached
You won't need to have $number in the addOne Function
There are two alternatives
If you don't want to keep $number as static then you can change addOne to a non-static method and access using $this->
class addClass
{
public $number = 0;
public function addOne()
{
$this->number = $this->number + 1;
if ($this->number == 7) {
return 'This is 7';
}
}
}
Or if you want addOne to be static then you can declare $number as static and access using self::
class addClass
{
private static $number = 0;
public static function addOne()
{
self::number = self::number + 1;
if (self::number == 7) {
return 'This is 7';
}
}
}
Please bear in mind:
1) The $number parameter in the addOne() method is taking precedence over the $number member in the addClass() parameter.
2) The sentence $number = $number++ is no affecting the variable $number at all, because it is first being assigned.
3) The addOne() method doesn't need to be static, unless is intended to be used without an instance of the class addClass.
4) Static variables only need to be initialize once, refer to the php manual for more information on the static keyword: http://php.net/manual/en/language.oop5.static.php
5) You cannot reference member variables inside a static method (e.g. using $this), because static methods have "class scope" and they are meant to be used without any instance of such class. On the other hand, non static methods require an instance of the class and they can reference members of the class by using $this.
6) Here's an example of how you can do this:
<?php
class addClass{
public function addOne($number) {
static $limit = 0;
if (!isset($limit)) {
$limit = $number;
}
if ($limit+1 == 7) {
return "Maximum limit reached";
} else {
$limit = $number+1;
}
}
}
$a = new addClass();
for($i = 0; $i< 7; $i++) {
echo $i+1, " => ", $a-> addOne($i), PHP_EOL;
}

How to get output of count variable?

<?php
$count=0;
class My extends Thread
{
private $myid;
// ini_set('max_execution_time', 0);
//echo date("Y-m-d H:i:s")."<br/>";
public function __construct($id)
{
$this->myid = $id;
}
public function run()
{
for($t=0;$j+$t<=100;$t+=10){ //future buy
for($k=0;$j+$t+$k<=100;$k+=10){//future sell
for($l=1;$l<=14;$l++){ // strike
for($m=0;$j+$k+$m<=300;$m+=10){ //put buy
for($n=1;$n<=14;$n++){ // strike
for($o=0;$o<=300;$o+=10){ // call buy
for($p=1;$p<=14;$p++){ //strike
if($p==$l)
continue;
for($q=0;$q<=300;$q+=10){ // put sell
for($r=1;$r<=14;$r++){ // strike
if($r==$n)
continue;
for($s=0;$s<=300;$s+=10){ // call buy
$count ++;
}
}
}
}
}
}
}
}
}
}
}
}
echo date("Y-m-d H:i:s")."<br/>";
$mycalls = [];
for($i=0;$i<=100;$i+=10)
{
$mycalls[$i]= new My($i);
$mycalls[$i]->start();
$mycalls[$i]->join();
}
echo date("Y-m-d H:i:s")."<br/>";
echo "<br>";
echo $count;
?>
Call run method of My class. and it should be either return $count or echo $count.
Not sure I completely understand what you mean by "how to get output of count variable", but I see a number of problems there might occur.
1) $count is a global variable and not a class or a method variable, which menas that simply adding 1 to count in th run method will not do any changes in $count outside the class definition.
2) I don't see any place where run method that updates $count (despite the fact that it is outside the class) variable is called.
3) Even if run method is somewhere called you have to add a line global $count at the beginning of run method.
4) I would suggest you store the $count internally in the class and return it with a function, which would mean that the class looks something like this:
Class My extends Thread{
protected $count = 0;
public function run(){
//...
$this -> count++;
//...
}
public function getCount(){
return $this -> count();
}
}
And then get the count value from the class instance:
$myInstance = new My();
$myInstance -> run();
$someCount = $myInstance -> getCount();
Due to the fact that you are creating 101 instances of my, the code would look something like this:
$mycalls = [];
$count = 0;
for($i=0;$i<=100;$i+=10)
{
$mycalls[$i]= new My($i);
$mycalls[$i]->start();
$mycalls[$i]->join();
$count += $mycalls[$i] -> getCount();
}
echo $count;

PHP pass variable outside of function without global variables

Let's say I have a function in php like this:
<?php function hello() {
$x = 2;
}
and I want to use that variable outside of this function without using global, since I've heard it's a bad idea because of it's security issues. (right?).
Anyway, what is the best way to get this value out? I would be able to do this in java by using "this". But not sure how that works in PHP. Thanks.
Update:
This is the code I needed help with:
<?php
require('includes/connect.php');
function connectHouseObjects() {
global $mysqli;
/* Register a prepared statement */
if ($stmt = $mysqli->prepare('SELECT x FROM house_room1 WHERE user_id = ?')) {
/* Bind parametres */
$stmt->bind_param('i', $user_id);
/* Insert the parameter values */
$user_id = 1;
/* Execute the query */
$stmt->execute();
/* Bind resultatet */
$stmt->bind_result($x);
while ($stmt->fetch()) {
//looping through the x's and y's
}
/* Close statement */
$stmt->close();
return $x;
} else {
/* Something went wrong */
echo 'Something went terrible wrong' . $mysqli->error;
}
}
?>
John Conde is right but to show you the code it would be
<?php
function hello() {
$x = 2;
return $x;
}
$var = hello();
echo $var;
?>
You can simply return your data:
function hello() {
$x = 2;
return $x;
}
and use its result wherever you want;
$x=hello();
Take this for example:
<?php
function hello(){
$x=2;
//this is where you get it out
return $x;
}
//here we are outside the function
$x = hello();
//$x now equals 2;
?>
Returning the variable from the function allows you to call the function and assign it outside.
Going more object oriented:
<?php
class Talk
{
protected $message;
public function setMessage($message){
//this will set your class variable to what ever is in $message
$this->message = $message;
}
public function getMessage()
{
//This will give you what ever your current message is
return $this->message;
}
}
//Then to use this you could do
$talk = new Talk();
//That sets up $talk to be an instance of the talk class
$talk->setMessage('Hello');
//This will then sets the message in talk to hello then to retrieve it just do
$message = $talk->getMessage();
//Now outside the class we have a variable $message that contains 'Hello'
You may also create a class, just like in Java, and use a class variable that can be accessed from other functions in that class.
You can simply return the value outside the function:
<?php
function hello() {
$x = 2;
return $x;
}
$x = hello();
If you want to return more than one value, you can use the list() function, while returning values as an array:
<?php
function hello() {
$x = 2;
$y = 3;
return array($x, $y);
}
list($x, $y) = hello();
You can find more information about the list() in the PHP manual

php global variable and instance variable utilization

I'm having hard time accomplishing one simple task. I have a method that would generate random number and depending on the outcome assign specific outcome to an array variable. What i want to do is get that array variable through instance method which would be called from the other class.
<?php
class MyClass
{
public $results = array(array());
public function simulated_games()
{
$game_series1=array(23,34,56);
$game_series2=array(31,42,67);
$iter_wins=array(array());
for($i=0; $i<10;$i++)
{
$random = rand(0,100);
for($b=0; $b<1;$b++)
{
if($random <= $game_series1[0])
{
$iter_wins[$i][$b]=3;
}
else if($random <= $game_series2[0]+$game_series2[1])
{
$iter_wins[$i][$b]=1;
}
}
}
$results=$iter_wins;
}
>here i create method just to return variable
public function get_simulated_games()
{
return $this->results;
}
}
<?php
$a= new MyClass();
$a->simulated_games();
$array = array();
>here is the issue, it return just 1, but supposed to return range numbers
$array=$a->get_simulated_games();
for($f=0; $f<sizeof($array);$f++)
{
for($g=0; $g<5;$g++)
{
echo $array[$f][$g];
}
echo '<br>';
}
?>
You have the error in results.
You modify interal function variable which is not set instead of class variable
change
$results=$iter_wins;
to
$this->results=$iter_wins;

Passing variable between functions - php

Below is an edited version of my actual code:
<?php
include ('login_info.php');
class modernCMS {
var $host;
var $username;
var $password;
var $db;
var $url;
function connect(){
$con = mysql_connect($this->host, $this->username, $this->password);
mysql_select_db($this->db, $con) or die(mysql_error());
mysql_set_charset('utf8');
}
function get_coordinates(){
$sql ="select lat, lng from postcodes LIMIT 1;";
$res = mysql_query($sql) or die(mysql_error());
while($row = mysql_fetch_assoc($res)){
$lat = $row['lat'];
$lng = $row['lng'];
}
}
function get_name(){
$sql ="select name from places WHERE lat=$lat AND lng=$lng LIMIT 1;";
$res = mysql_query($sql) or die(mysql_error());
while($row = mysql_fetch_assoc($res)){
$name = $row['name'];
echo $name;
}
}
?>
Then within a separate document i have an include for the file above. I call the function get name using the following:
<?=$obj->get_name()?>
get_name actually contains a calculation for calculating the distance between two points however because its a lengthy calculation i have left it out of the example above.
Its important that i can just use $obj->get_name() to get the output for $lat and $lng
Functions operate within function scope, so the variables that you've set in get_coordinates() are local variables. To create global variables, you can use the global keyword:
<?php
function get_coordinates()
{
global $lat, $lng;
$lat = 25;
$lng = 5;
}
function display_coordinates()
{
global $lat, $lng;
echo $lat;
echo $lng;
}
get_coordinates();
display_coordinates();
Or $GLOBALS array:
<?php
function get_coordinates()
{
$GLOBALS['lat'] = 25;
$GLOBALS['lng'] = 5;
}
function display_coordinates()
{
echo $GLOBALS['lat'];
echo $GLOBALS['lng'];
}
get_coordinates();
display_coordinates();
However, this may not be the best way to set/access these variables because any function can change their state at any time, and you must call one function to set them before calling the other to display them. If you can describe your specific goal, you might be able to get better advice.
One better way to accomplish this is to use a class, and pass the object where you need it (this simple example does not demonstrate proper encapsulation, but is a good starting point):
<?php
class Coordinates {
public $lat;
public $lng;
public function __construct($lat, $lng) {
$this->lat = $lat;
$this->lng = $lng;
}
public function display_coordinates() {
echo $this->lat . "\n";
echo $this->lng . "\n";
}
}
function get_coordinates() {
return new Coordinates(25, 5);
}
$coords = get_coordinates();
$coords->display_coordinates();
function output_coordinates($coordinates) {
$coordinates->display_coordinates();
}
output_coordinates($coords);
Another way that is commonly used in PHP is to pass things in associative arrays (arrays with strings for indexes). I don't prefer this usually, because the array does not declare what it intends to hold, but it is an option:
<?php
function get_coordinates() {
return array('lat' => 25, 'lng' => 5);
}
function output_coordinates($coordinates) {
echo $coordinates['lat'] . '\n';
echo $coordinates['lng'] . '\n';
}
$coords = get_coordinates();
output_coordinates($coords);
You're running into a scoping issue. The variables are only available to the function that declared them. To make them available, you can either pass the variables to the function explicitly (you need to make sure you always call get_coordinates() before display_coordinates() though, otherwise you'll have undefined values), or using global variables (bad idea).
The best method is probably to make a class for it (although it depends on how you intend to use it). Your variables will always be in scope, and you won't run the risk of trying to run the display_coordinates() function before you've initialized the variables.
class Coordinate
{
// These are the variables where the coords will be stored.
// They are available to everything within the {}'s after
// "class Coordinate" and can be accessed with
// $this->_<varname>.
protected $_lat;
protected $_long;
// This is a special function automatically called when
// you call "new Coordinate"
public function __construct($lat, $long)
{
// Here, whatever was passed into "new Coordinate" is
// now stored in our variables above.
$this->_lat = $lat;
$this->_long = $long;
}
// This takes the values are stored in our variables,
// and simply displays them.
public function display()
{
echo $this->_lat;
echo $this->_long;
}
}
// This creates a new Coordinate "object". 25 and 5 have been stored inside.
$coordinate = new Coordinate(25, 5); // 25 and 5 are now stored in $coordinate.
$coordinate->display(); // Since $coordinate already "knows" about 25 and 5
// it can display them.
// It's important to note, that each time you run "new Coordinate",
// you're creating an new "object" that isn't linked to the other objects.
$coord2 = new Coordinate(99, 1);
$coord2->display(); // This will print 99 and 1, not 25 and 5.
// $coordinate is still around though, and still knows about 25 and 5.
$coordinate->display(); // Will still print 25 and 5.
You should read up on Variable Scope and Classes and Objects to understand more about this.
To put this together with your original code, you would do something like this,
function get_coordinates()
{
return new Coordinate(25, 5);
}
function display_coordinates($coord)
{
$coord->display();
}
$c = get_coordinates();
display_coordinates($c);
// or just "display_coordinates(get_coordinates());"
Edit after question updated
There are a few bad practices in your code, but here's some quick steps to get what you want.
// Copy the Coordinate class from my answer above, but add two new
// lines before the final "}"
public function getLatitude() { return $this->_lat; }
public function getLongitude() { return $this->_long; }
// Put the Coordinate class definition before this line
class modernCMS {
/////
// In your code, after this line near the top
var $url;
// Add this
var $coord;
/////
// In your get_coordinates(), change this...
$lat = $row['lat'];
$lng = $row['lng'];
// To this...
$this->coord = new Coordinate($lat, $lng);
/////
// In your get_name(), add two lines to the start of your function.
function get_name(){
$lat = $this->coord->getLatitude();
$lng = $this->coord->getLongitude();
Unrelated to your question, but you should also read about "SQL Injection" as query in get_name() is vulnerable. Not a big deal here, since the data comes from your other query anyway, but still good practice not to use parameters directly in a query string.
What about Session?
https://www.php.net/manual/en/reserved.variables.session.php
Creating New Session
session_start();
/*session is started if you don't write this line can't use $_Session global variable*/
$_SESSION["newsession"]=$value;
Getting Session
session_start();
/*session is started if you don't write this line can't use $_Session global variable*/
$_SESSION["newsession"]=$value;
/*session created*/
echo $_SESSION["newsession"];
/*session was getting*/
Updating Session
session_start();
/*session is started if you don't write this line can't use $_Session global variable*/
$_SESSION["newsession"]=$value;
/*it is my new session*/
$_SESSION["newsession"]=$updatedvalue;
/*session updated*/
Deleting Session
session_start();
/*session is started if you don't write this line can't use $_Session global variable*/
$_SESSION["newsession"]=$value;
unset($_SESSION["newsession"]);
/*session deleted. if you try using this you've got an error*/
One way of doing it:
function get_coordinates(&$lat, &$lng)
{
$lat = 25;
$lng = 5;
}
function display_coordinates($lat, $lng)
{
echo $lat;
echo $lng;
}
$lat = 0;
$lng = 0;
// assign values to variables
get_coordinates( $lat, $lng );
// use function to display them...
display_coordinates ($lat, $lng);
Create a Coordinate.class.php file:
<?php
class Coordinate {
var $latitude;
var $longitude;
public function getLatitude() {
return $this->latitude;
}
protected function setLatitude($latitude) {
$this->latitude = floatval($latitude);
}
public function getLongitude() {
return $this->longitude;
}
protected function setLongitude($longitude) {
$this->longitude = floatval($longitude);
}
public function __construct() {
// Overload
if (func_num_args() == 2) {
$this->setLatitude(func_get_arg(0));
$this->setLongitude(func_get_arg(1));
}
// Default
else {
$this->setLatitude(0);
$this->setLongitude(0);
}
}
public function displayCoordinate() {
printf("Latitude: %.2f, Longitude: %.2f\n",
$this->getLatitude(),
$this->getLongitude());
}
}
function main() {
$c = new Coordinate (25, 5);
$c->displayCoordinate();
}
main();
?>
Change of another post.. I think the better way:
function get_coordinates()
{
return array(
"lat" => 25,
"lng" => 5
);
}
function display_coordinates($latLongArray)
{
echo $latLongArray['lat'];
echo $latLongArray['lng'];
}
// assign values to variables
$latLongArray = get_coordinates();
// use function to display them...
display_coordinates ($latLongArray);

Categories