Functions are not working due to undefined variables and I have no clue why that is. I think I just don't get the scope at which objects/classes work. Do I need to make a reference like $obj from which to call the functions? If so why is it not working in this example?
<?php
class employee {
// Properties
public $name;
public $salary = 0;
// Methods
function set_name($name) {
$this->name = $name;
}
function get_name() {
return $this->name;
}
function set_salary($salary) {
$this->salary = $salary;
}
function get_salary() {
return $this->salary;
}
function populate()
{
$worker = array();
$worker[0] = new employee();
$worker[0]->set_name('Linda');
$worker[0]->set_salary(5800);
$worker[1] = new employee();
$worker[1]->set_name('Manuel');
$worker[1]->set_salary(2750);
$worker[2] = new employee();
$worker[2]->set_name('Luis');
$worker[2]->set_salary(3200);
$worker[3] = new employee();
$worker[3]->set_name('Carly');
$worker[3]->set_salary(2999);
$i = 0;
}
function checkTaxes()
{
while ($i < 4)
{
echo "Name: " . $worker[$i]->get_name();
echo " - Salary: " . $worker[$i]->get_salary();
if ($worker[$i]->get_salary() >= 3000)
{
echo " - You have to pay taxes!<br><br>";
}
else
{
echo " - You don't have to pay taxes!<br><br>";
}
$i++;
}
}
}
$obj = new employee;
$obj->populate();
$obj->checkTaxes();
?>
$worker is undefined in checkTaxes()
If you want to use $worker in checkTaxes() or other functions, you should define $worker in class employee with private $worker = [];, just like $name and $salary.And after that, you can update it in populate() with $this->worker[0] = xxx;, and read it in checkTaxes() with $this->worker[$i]->getxxx.
Related
I got some problem and I don't know how to fix it.
this is sample for the problem
class DancingClass {
private static $associate = [];
private static $first;
public static function first($param) {
self::$first = $param;
return new self;
}
public function second($param) {
self::$associate["second"] = $param;
return new self;
}
public function finish() {
var_dump(self::$associate["second"]);
$sec = self::$associate["second"] | "";
$all = self::$first . " ditemani oleh " . $sec;
return $all;
}
}
Then I call with chaining method
$callingClass = new DancingClass;
echo $callingClass::first("lucky")->second("adhitya")->finish(); // Return "lucky ditemani oleh adhitya"
echo "<br/>";
echo $callingClass::first("fatur")->finish(); // Return "fatur ditemani oleh"
but I got result like this
When you call second() method it sets variable on the same class instance that you call later.
Maybe you should try:
echo ((new DancingClass())->first(...)->second(...)->finish();
echo ((new DancingClass())->first(...)->finish()
How pass parameter to PHP class by class()::function()?
class greenHouse{
public function __construct(connection $con){
}
public function show(){
}
}
$nameclass = 'greenHouse';
$namefunction = 'show';
$nameclass::$namefunction();
works
$nameclass = 'greenHouse';
$namefunction = 'show';
$nameclass($con)::$namefunction();
doesn't work
I want to pass a parameter to the class with $nameclass($con)::$namefunction();. How do I do that in PHP?
You are trying to call a function statically with that notation...
$nameclass = 'greenHouse';
$namefunction = 'show';
$class = new $nameclass($con);
$class->$namefunction();
You can instantiate an object and immediately discard it by calling new within braces:
class Test
{
private $name;
function __construct($name)
{
$this->name = $name;
}
function speak()
{
echo $this->name;
}
function __destruct()
{
echo 'dead';
}
}
$class='Test';
$method='speak';
(new $class('David'))->$method();
echo ' is ';
$temp = new $class('John');
$temp->$method();
echo ' is ';
//Daviddead is John is dead
So in your case:
(new $nameclass($con))->$namefunction();
I want to create a class that can remove duplicate items but uses pthreads I have an array with some duplicated lines and put them into a thread each line and here is my code.
header("Content-type: text/plain");
class Arr {
public $my_variable = array();
public function add($value) {
$this->my_variable[$value] = 1;
return $this->my_variable;
}
public function check($value)
{
if(isset($this->my_variable[$value])){
return true;
} else {
return false;
}
}
}
class workerThread extends Thread
{
public $arr;
public function __construct($i){
$this->i = str_replace("\r","",$i);
$this->i = str_replace("\n","",$this->i);
$this->arr = new Arr();
}
public function run()
{
if($this->arr->check($this->i)!==true)
{
$add = $this->arr->add($this->i);
echo date('H:i:s') . ' - '. $this->i . " - (".count($add).")\r\n";
}
}
}
$mailExp = array(
'talunays#gmail.com',
'talunays#gmail.com',
'talunays#gmail.com',
'talunays#gmail.com',
'talunays#gmail.com'
);
$total = count($mailExp);
for($i=0;$i<$total-1;$i++)
{
$workers[$i]=new workerThread($mailExp[$i]);
$workers[$i]->start();
}
But it doesn't work, duplicate lines still there and cannot be removed...
You should use construct only to set your private $this variables.
Make the logic inside the run function and use array_unique.
Let the workers come back with join() and retrieve the unduplicated arrays at this point.
Consider the following code:
class Project
{
public $ProjectID;
}
class Work
{
public $WorkID;
}
public function insert($pData, $tableName)
{
//generate insert here
$pData->{$tableName . 'ID'} = $result->getId();
}
$p = new Project();
$w = new Work();
insert($w, 'Work');
insert($p, 'Project');
echo $p . ' -- ' . $w;
Now how would I go about setting the variable in a dynamic way? I'm building a data layer. The $pData->{$tableName . 'ID'} doesn't seem to work...
So, you want to dynamically call setters?
$y = new stdClass();
$y->prop1 = "something";
$targetProperty = "prop1";
$y->$targetProperty = "something else";
echo $y->prop1;
//Echos "something else"
That what you're looking for?
This is what you're looking for:
public function set_to_seven($p_data, $name)
{
$name = $name . 'ID';
$p_data->$name = 7;
}
The property name can be a variable. Just like functions:
$p = 'print_r';
$p('StackOverflow');
For future reference: if you need this statically, you're looking for variable variables,
public function set_to_seven($p_data, $name)
{
$name = $name . 'ID';
$p_data::$$name = 7;
}
You can set public properties by accessing them just like any other definition in the class.
$p = new Project();
$p->ProjectID = 5;
echo $p->ProjectID; // prints 5
http://php.net/manual/en/language.oop5.visibility.php
This worked for me.
class Project {
public $ProjectID;
}
function setToSeven($pData, $name) {
$pData->{$name . "ID"} = 7;
}
$p = new Project();
setToSeven($p, 'Project');
echo $p->ProjectID;
You just need to echo the variable or set up a toString function on the class to echo the class. To String works like this
class Project {
public $ProjectID;
public function __toString(){
return (string)$this->ProjectID;
}
}
function setToSeven($pData, $name) {
$pData->{$name . "ID"} = 7;
}
$p = new Project();
setToSeven($p, 'Project');
echo $p;
How can i pass a class as a parameter in my function
So far i've tried
$sc = new SampleClass();
SampleFunction($sc);
function SampleFunction(&$refClass)
{
echo $refClass->getValue();
}
this is a simplified example of what im doing.. i actually have to do complex procedures inside this sample function. I'm not getting any response from the sample function. What am i doing wrong? thank you
UPDATE
char.php
class Charss {
var $name=0;
var $hp=500;
var $spd=10;
var $rtime=10;
var $dmg=10;
function __construct( $name, $hp, $spd, $rtime , $dmg) {
$this->name = $name;
$this->hp = $hp;
$this->spd = $spd;
$this->rtime = $rtime;
$this->dmg = $dmg;
}
function get_name() {
return $this->name;
}
function set_name($new_name) {
$this->name = $new_name;
}
function get_hp() {
return $this->hp;
}
function set_hp($new_hp) {
$this->hp = $new_hp;
}
function get_spd() {
return $this->spd;
}
function set_spd($new_spd) {
$this->spd = $new_spd;
}
function get_rtime() {
return $this->rtime;
}
function set_rtime($new_rtime) {
$this->rtime = $new_rtime;
}
function get_dmg() {
return $this->get_dmg;
}
function set_dmg($new_dmg) {
$this->dmg = $new_dmg;
}
}
myclass.php
require("char.php");
class Person {
function try_process()
{
$chr1 = new Charss("Player1",500,3,0,50);
$chr2 = new Charss("Player2",500,6,0,70);
while ($chr1->get_hp() > 0 && $chr2->get_hp() > 0)
{
$sth = min($chr1->get_rtime(), $chr2->get_rtime());
if ($chr1->get_rtime() == 0 && $chr2->get_rtime() > 0)
{
exit;
Fight($chr1,$chr2);
$chr1->set_rtime($chr1->get_spd());
}
elseif ($chr2->get_rtime() == 0 && $chr1->get_rtime() > 0)
{
Fight($chr2,$chr1);
$chr2->set_rtime($chr2->get_spd());
}
else
{
Fight($chr1,$chr2); #having trouble with this
$chr1->set_rtime($chr1->get_spd());
}
$chr1->set_rtime($chr1->get_rtime() - $sth);
$chr2->set_rtime($chr2->get_rtime() - $sth);
}
}
function Fight($atk,$def)
{
$def->set_hp($def->get_hp() - $atk->get_dmg());
echo $atk->get_name() . " attacked " . $def->get_name() . " for " . $atk->get_dmg() . " damage";
}
}
so im calling the function try_process on button click
What you're actually doing there is passing an object, not a class.
$sc = new SampleClass();
creates an instance of SampleClass, aka an object.
I assume there's some error being thrown elsewhere as what you have is correct.
I tested the following code and got the expected output:
class SampleClass
{
public function getValue()
{
return 4;
}
}
$sc = new SampleClass();
SampleFunction($sc);
function SampleFunction(&$refClass)
{
echo $refClass->getValue();
}
Output: 4
If you provide more details of your actual code we might be able to determine the problem.
I can't see anything wrong with your code
using &$refClass is however is not recommended and I guess willbe removed from future iteration of PHP version
but here is an example
class objects are passed as reference I suppose so no need of '&'
http://ideone.com/GbmUy
Why is the function argument a reference? Probably shouldn't be.
Other than that, there's nothing wrong with you posted, so the error is likely within SampleClass.
Others have answered pretty well, but this is a silly little example to show you how to modify the class (either by calling a property setter, or setting public properties directly)
class foo {
private $member1;
public $member2;
public function __construct($member1,$member2) {
$this->member1=$member1;
$this->member2=$member2;
}
public function SetMember1($value) {
$this->member1 = $value;
}
public function GetMember1() {
return $this->member1;
}
}
function SetMembers(foo $obj, $member1, $member2) {
// Call a setter
$obj->SetMember1($member1);
// Set a member variable directly
$obj->member2 = $member2;
}
$obj = new foo('default member 1', 'default member 2');
echo "member1 (before): {$obj->GetMember1()}\n";
echo "member2 (before): {$obj->member2}\n";
// Change values
SetMembers($obj, 'new member1', 'new member2');
echo "member1 (after): {$obj->GetMember1()}\n";
echo "member2 (after): {$obj->member2}\n";
This will output:
member1 (before): default member 1
member2 (before): default member 2
member1 (after): new member1
member2 (after): new member2