<?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;
Related
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;
}
My current code:
public function countThreads() {
$count = $this->threads->count();
if ($this->hasSubforum()) {
foreach ($this->subforums as $subforum) {
$count += $this->countThreads($subforum);
}
}
return $count;
}
I am currently accessing the "thread" as $this inside my model. I need to pass in the $subforum to itself but how can I do that in a class?
In my controller, I'm simply doing:
$forum = Forum::where('id', $id)->first();
$forum->countThreads();
How can I do recursion with this? thanks!
You don't need to pass any arguments*, you can call the countThreads method on the subforum $subforum->countThreads()
public function countThreads()
{
$count = $this->threads->count();
if ($this->hasSubforum()) {
foreach ($this->subforums as $subforum) {
$count += $subforum->countThreads();
}
}
return $count;
}
If you really want to pass it in as an argument, the correct way would be to write it as a service outside of the model
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;
I am working with lemonade-php. My code is at https://github.com/sofadesign/limonade.
The issue I am having is when I try to run
class syscore {
public function hello(){
set('post_url', params(0));
include("./templates/{$this->temp}/fullwidth.tpl");
return render('fullwidth');
}
}
which then loads the fullwidth.tpl and runs function fullwidth
fullwidth.tpl
<?php
global $post;
function fullwidth($vars){
extract($vars);
$post = h($post_url);
}
print_r($this->post($post));
?>
it seems to pass the $post_url but I can not pass it again to the print_r($this->post($post));
However when I try to run print_r($this->post($post)) inside the fullwidth function it says it can not find the post() function
I have tried a number of things like below
function fullwidth($vars){
extract($vars);
$post = h($post_url);
print_r(post($post));
}
I tried re connecting to the syscore by
$redi = new syscore();
$redi->connection() <-- this works
$redi->post($post) <-- this does not
Here is my full class syscore
class syscore {
// connect
public function connect($siteDBUserName,$siteDBPass,$siteDBURL,$siteDBPort, $siteDB,$siteTemp){
for ($i=0; $i<1000; $i++) {
$m = new Mongo("mongodb://{$siteDBUserName}:{$siteDBPass}#{$siteDBURL}:{$siteDBPort}", array("persist" => "x", "db"=>$siteDB));
}
// select a database
$this->db = $m->$siteDB;
$this->temp = $siteTemp;
}
public function hello(){
set('post_url', params(0));
include("./templates/{$this->temp}/fullwidth.tpl");
return render('fullwidth');
}
public function menu($data)
{
$this->data = $data;
$collection = $this->db->redi_link;
// find everything in the collection
//print $PASSWORD;
$cursor = $collection->find(array("link_active"=> "1"));
if ($cursor->count() > 0)
{
$fetchmenu = array();
// iterate through the results
while( $cursor->hasNext() ) {
$fetchmenu[] = ($cursor->getNext());
}
return $fetchmenu;
}
else
{
var_dump($this->db->lastError());
}
}
public function post($data)
{
$this->data = $data;
$collection = $this->db->redi_posts;
// find everything in the collection
//print $PASSWORD;
$cursor = $collection->find(array("post_link"=> $data));
if ($cursor->count() > 0)
{
$posts = array();
// iterate through the results
while( $cursor->hasNext() ) {
$posts[] = ($cursor->getNext());
}
return $posts;
}
else
{
var_dump($this->db->lastError());
}
}
}
It looks like you are having some issues understanding the execution path that PHP is taking when trying to render your template. Let's take a more in-depth look, shall we?
// We're going to call "syscore::hello" which will include a template and try to render it
public function hello(){
set('post_url', params(0)); // set locals for template
include("./templates/{$this->temp}/fullwidth.tpl"); // include the template
return render('fullwidth'); // Call fullwidth(array('post_url' => 'http://example.com/path'))
}
The trick to solving this one is to understand how PHP include works. When you call include("./templates/{$this->temp}/fullwidth.tpl") some of your code is executing in the scope of the syscore object, namely:
global $post;
and
print_r($this->post($post));
fullwidth is created in the global scope at this point, but has not yet been called. When render calls fullwidth you're no longer in the syscore scope, which is why you cannot put $this->post($post) inside without triggering an error.
Ok, so how do we solve it? Glad you asked.
We could probably refactor syscore::post to be a static method, but that would then require syscore::db to be static, and always return the SAME mongodb instance (singleton pattern). You definitely do not want to be creating 1000 Mongo instances for each syscore instance.
We could just abuse the framework. A much poorer solution, but it will get the job done.
fullwidth.tpl
<?php
function fullwidth($vars){
$post_url = ''; // put the variables you expect into the symbol table
extract($vars, EXTR_IF_EXISTS); // set EXTR_IF_EXISTS so you control what is added.
$syscore_inst = new syscore;
$post = h($post_url);
print_r($syscore->post($post)); // I think a puppy just died.
}
Look the second way is a complete hack, and writing code like that will probably mean you won't get promoted. But it should work.
But let's say you wanted to get promoted, you would make good, shiny code.
// Note: Capitalized class name
class Syscore {
protected static $_db;
public static function db () {
if (! static::$_db) {
static::$_db = new Mongo(...);
}
return static::$_db;
}
// #FIXME rename to something more useful like "find_posts_with_link"
public static post($url) {
$collection = static::db()->redi_posts;
// find everything in the collection
$cursor = $collection->find(array("post_link"=> $url));
// Changed to a try-catch, since we shouldn't presume an empty find is
// an error.
try {
$posts = array();
// iterate through the results
while( $cursor->hasNext() ) {
$posts[] = ($cursor->getNext());
}
return $posts;
} catch (Exception $e) {
var_dump($this->db->lastError());
}
}
}
Then in your fullwidth function, we don't have to do any of that stupid nonsense of treating an instance method like it were a static method.
function fullwidth($vars){
$post_url = ''; // put the variables you expect into the symbol table
extract($vars, EXTR_IF_EXISTS); // set EXTR_IF_EXISTS so you control what is added.
$post = h($post_url);
print_r(Syscore::post($post)); // static method. \O/ Rainbows and unicorns.
}
I am building an API where the user requests a 'command', which is passed into a class. Assuming the command matches a PUBLIC function, it will execute successfully.
If the command matches a PROTECTED function, it needs to throw an error.
The idea is that functions can be disabled by changing them from PUBLIC to PROTECTED, rather than renaming them or removing them.
I currently do this, but it doesn't matter if the command is public or protected.
<?php
/**
* Look for Command method
*/
$sMethod = "{$sCommand}Command";
if (method_exists($this, $sMethod))
{
/**
* Run the command
*/
return $this->$sMethod($aParameters);
}
Simply use ReflectionMethod:
/**
* Look for Command method
*/
if (method_exists($this, $sMethod))
{
$reflection = new ReflectionMethod($this, $sMethod);
if (!$reflection->isPublic()) {
throw new RuntimeException("The called method is not public.");
}
/**
* Run the command
*/
return $this->$sMethod($aParameters);
}
You can use the is_callable function to determine if the protection level should limit you: Example:
<?php
class FooBar {
protected function Foo() { return; }
public function Bar() { return; }
}
$foo = new FooBar();
var_dump(is_callable(array($foo, 'Foo')));
var_dump(is_callable(array($foo, 'Bar')));
Though you can not differentiate if the method is private or protected, you can test if public versus not using an external method using is_callable. I made a comparison with "meze" answer.
So:
function testIfCallable($object, $method) {
return is_callable(array($object, $method));
}
function testIfCallable2($object, $method) {
if (method_exists($object, $method))
{
$reflection = new ReflectionMethod($object, $method);
return $reflection->isPublic();
}
return false;
}
class Test {
private function privateMethod() {
}
protected function protectedMethod() {
}
public function publicMethod() {
}
public function testAccessibility() {
if (testIfCallable($this, 'privateMethod')) echo "YYY<br>"; else echo 'NNN<br>';
if (testIfCallable($this, 'protectedMethod')) echo "YYY<br>"; else echo 'NNN<br>';
if (testIfCallable($this, 'publicMethod')) echo "YYY<br>"; else echo 'NNN<br>';
}
public function testAccessibility2() {
if (testIfCallable2($this, 'privateMethod')) echo "YYY<br>"; else echo 'NNN<br>';
if (testIfCallable2($this, 'protectedMethod')) echo "YYY<br>"; else echo 'NNN<br>';
if (testIfCallable2($this, 'publicMethod')) echo "YYY<br>"; else echo 'NNN<br>';
}
public function testSpeedAccessibility() {
return $results = [
testIfCallable($this, 'privateMethod'),
testIfCallable($this, 'protectedMethod'),
testIfCallable($this, 'publicMethod')
];
}
public function testSpeedAccesibility2() {
return $results = [
testIfCallable2($this, 'privateMethod'),
testIfCallable2($this, 'protectedMethod'),
testIfCallable2($this, 'publicMethod')
];
}
}
The method testIfCallable shall be included in a Common class or something similar which you have in your own toolkit because global methods aren't recommended.
I use this in conjunction with the magic methods __get and __set to ensure a public "get/set" method exists.
Tests :
//Test functionality
$t = new Test();
$t->testAccessibility();
$t->testAccessibility2();
//Test speed
$start = microtime(true);
for($i = 0; $i < 10000; $i++) {
$t->testSpeedAccessibility();
}
echo "Is Callable way: " . (microtime(true) - $start) . "ms<br>";
$start = microtime(true);
for($i = 0; $i < 10000; $i++) {
$t->testSpeedAccesibility2();
}
echo "Reflection way: " . (microtime(true) - $start) . "ms<br>";
Outputs:
NNN
NNN
YYY
NNN
NNN
YYY
Is Callable way: 0.23506498336792ms
Reflection way: 0.45829010009766ms
Final thoughts
If you need to test between all the visibility possibilities, your only way to go is to use testIfCallable2, so the "meze"'s answer. Otherwise, my way is about twice faster. As your question was only between public or not, you could benefit using this. Saying that, if you don't use it often, the difference is not significant.